728x90
1. 문제
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
2. PS
- stack을 이용한 수열만들기와 '+'와 '-' 데이터를 저장할 배열을 만듬.
- targetNum을 만날때 까지 1~n 까지의 숫자를 push.
- 'NO'가 되는 조건이 핵심인데, 본인은 stack.size와 제시한 n을 비교하여 해결함.
- 코드적으로 더 쉽게하는 방법이 있을 것 같은데, 나중에 다시 한번 풀어봐야 할 것 같음.
#include <iostream>
#include <stack>
#include <deque>
#include <algorithm>
using namespace std;
int main() {
cin.tie(NULL);
ios_base::sync_with_stdio(false);
int n, targetNum, num=1;
stack<int> st1;
deque<char> pmstr;
deque<int> dq2;
cin >> n;
for(int i = 0 ; i < n; i++) {
cin >> targetNum;
dq2.push_back(targetNum);
}
bool no = false;
num = 1;
st1.push(num++);
pmstr.push_back('+');
for(int i = 0; i < n; i++) {
while(1) {
if(st1.empty()) {
st1.push(num++);
pmstr.push_back('+');
}
if(st1.top() == dq2[0]) {
st1.pop();
dq2.pop_front();
pmstr.push_back('-');
break;
}
st1.push(num++);
pmstr.push_back('+');
if(st1.size() > n) {
no = true;
break;
}
if(no) break;
}
}
if(!no) for(char c : pmstr) cout << c << '\n';
else cout << "NO";
}
'BOJ > C++' 카테고리의 다른 글
BOJ [C++]) 1021번 회전하는 큐 (0) | 2021.12.20 |
---|---|
BOJ [C++]) 2164번 카드2 (0) | 2021.12.20 |
BOJ [C++]) 1158번 요세푸스 문제 (0) | 2021.12.20 |
BOJ [C++]) 9012번 괄호 (0) | 2021.12.20 |
BOJ [C++]) 1406번 에디터 (0) | 2021.12.19 |