알고리즘 공부 및 문제 풀이/백준(BOJ)
[boj] 백준 2493 탑 - stack
yoonjiy
2022. 3. 25. 22:40
[문제]
https://www.acmicpc.net/problem/2493
2493번: 탑
첫째 줄에 탑의 수를 나타내는 정수 N이 주어진다. N은 1 이상 500,000 이하이다. 둘째 줄에는 N개의 탑들의 높이가 직선상에 놓인 순서대로 하나의 빈칸을 사이에 두고 주어진다. 탑들의 높이는 1
www.acmicpc.net
[풀이]
본인의 바로 왼쪽에 있는 탑부터 비교하도록 하기 위해 stack을 이용한다. 현재 탑의 높이보다 크면 출력, 작으면 pop()을 해주고, stack이 비면 왼쪽에 있는 탑들 중 신호를 받을 탑이 없다는 것이므로 0을 출력한다.
[코드]
#include <iostream>
#include <vector>
#include <cstring>
#include <algorithm>
#include <stack>
using namespace::std;
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int n;
stack<pair<int, int>> top;
cin >> n;
int height;
for(int i=1; i<=n; i++){
cin >> height;
while(!top.empty()){
if(top.top().second > height){
cout << top.top().first << " ";
break;
}
top.pop();
}
if(top.empty())
cout << "0 ";
top.push({i, height});
}
}