문제
https://www.acmicpc.net/problem/1874
1874번: 스택 수열
1부터 n까지에 수에 대해 차례로 [push, push, push, push, pop, pop, push, push, pop, push, push, pop, pop, pop, pop, pop] 연산을 수행하면 수열 [4, 3, 6, 8, 7, 5, 2, 1]을 얻을 수 있다.
www.acmicpc.net
소스코드
#include <iostream>
#include <algorithm>
#include <stack>
#include <vector>
using namespace std;
stack<int> st;
vector<char> v;
int main() {
ios_base::sync_with_stdio(false), cin.tie(NULL);
int n,cnt=1;
cin >> n;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
while (cnt <= x) {
v.push_back('+');
st.push(cnt);
cnt++;
}
if(x == st.top()) {
st.pop();
v.push_back('-');
}
else {
cout << "NO";
return 0;
}
}
for (int i = 0; i < v.size(); i++) {
cout << v[i] << "\n";
}
}
해설
처음에는 문제가 이해가지 않았지만, 차근히 이해해보니 입력값 x를 계속해서 입력받은 만큼 1~n까지의 숫자를 차례로 카운트하여 스택에 넣고 만약 스택에 넣은 값 중 가장 위에 있는 값과 x가 다를 경우는 절대로 출력할 수 없는 경우이니 바로 NO를 출력해준다.
'Algorithm > 자료구조' 카테고리의 다른 글
| [백준] 알고리즘 C++ 1764번 - 듣보잡문제 (0) | 2021.11.19 |
|---|---|
| [백준] 알고리즘 C++ 10989번 - 수 정렬하기3문제 (0) | 2021.11.10 |
| [백준] 알고리즘 C++ 11866번 - 요세푸스 문제 0문제 (0) | 2021.11.07 |
| [백준] 알고리즘 C++ 2164번 - 카드2문제 (0) | 2021.10.11 |
| [백준] 알고리즘 C++ 1654번 - 랜선 자르기문제 (0) | 2021.10.10 |
