본문 바로가기
Algorithm/C++

[백준 1874번] 스택 수열

by imagineer_jinny 2022. 4. 10.

1874번: 스택 수열 (acmicpc.net)

 

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 <stack>
#include <string>
using namespace std;
int main() {
    stack<int> s;
    int n;
    string ans;

    cin >> n;

    int m = 0;

    while (n--) {
        int x;
        cin >> x;
        if (x > m) {
            while (x > m) {
                s.push(++m);
                ans += '+';
            }
            s.pop();
            ans += '-';
        } else {
            bool found = false;
            if (!s.empty()) {
                int top = s.top();
                s.pop();
                ans += '-';
                if (x == top) {
                    found = true;
                }
            }
            if (!found) {
                cout << "NO" << '\n';
                return 0;
            }
        }
    }
    for (auto x : ans) {
        cout << x << '\n';
    }
    return 0;
}

'Algorithm > C++' 카테고리의 다른 글

[백준 1110번] 더하기 사이클  (0) 2022.04.21
[백준 17413번] 단어 뒤집기 2  (0) 2022.04.19
[백준 5635번] 생일  (0) 2022.04.09
[백준 9012] 괄호  (0) 2022.04.08
[백준 9093] 단어 뒤집기  (0) 2022.04.07

댓글