1 minute read

문제 접근

현재 높이를 읽고 스택 최상단의 높이와 비교합니다.
스택 상단의 높이가 현재 높이보다 작으면 더 높은 탑이 발견될 때까지 스택을 팝(pop)합니다.
스택 상단의 탑 인덱스를 출력합니다. 이는 신호를 수신할 수 있는 탑을 나타냅니다.
현재 탑(높이, 인덱스)을 스택에 푸쉬합니다.

예시

                입력: 6  1  8  5  9  2  4  3  7  10
스택 변화: 
1. | 100000001, 0 |                          -> 출력: 0
2. | 100000001, 0 | 6, 1                     -> 출력: 1
3. | 100000001, 0 | 8, 3                     -> 출력: 0
4. | 100000001, 0 | 8, 3 | 5, 4               -> 출력: 3
5. | 100000001, 0 | 9, 5                     -> 출력: 0
6. | 100000001, 0 | 9, 5 | 2, 6               -> 출력: 5
7. | 100000001, 0 | 9, 5 | 4, 7               -> 출력: 5
8. | 100000001, 0 | 9, 5 | 4, 7 | 3, 8         -> 출력: 7
9. | 100000001, 0 | 9, 5 | 7, 9               -> 출력: 5
10.| 100000001, 0 |10, 10                    -> 출력: 0

     출력 결과: 0  1  0  3  0  5  5  7  5  0

코드

#include <bits/stdc++.h>
#define ll long long
using namespace std;
#define X first
#define Y second
/*
미지인것 탑의 신호를 수신받는 탑의 번호

*/
stack<pair<int, int>> s;
int main(void) {
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    int n; cin >> n;

    s.push({ 100000001, 0 });
    for (int i = 1; i <= n; i++)
    {
        int height; cin >> height;
        while (s.top().first < height)
            s.pop();
        cout << s.top().second << " ";
        s.push({ height,i });
    }
    return 0;
}

Leave a comment