본문 바로가기

PS/BOJ

[C++] BOJ (백준) 1874 : 스택 수열

문제

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>

using namespace std;

int cnt = 1;
string res;
stack<int> st;

bool write(int n) {
    while (cnt <= n) {
        st.push(cnt);
        cnt++;
        res += "+\n";
    }
    if (st.top() == n) {
        st.pop();
        res += "-\n";
        return true;
    } else {
        return false;
    }
}

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(nullptr);

    int n;
    cin >> n;

    while (n--) {
        int tmp;
        cin >> tmp;
        if (!write(tmp)) {
            cout << "NO";
            return 0;
        }
    }

    cout << res;
    return 0;
}

 

설명

write 함수로 주어진 수를 만들기 위한 과정을 출력한다.
만들 수 없다면 false를 반환해 NO를 출력한다.