백준 1874번(by C++)

문제

백준 알고리즘 1874번



코드

#include <iostream>
#include <string>
#include <vector>
#include <stack>
#include <queue>
using namespace std;

int main() {
    int n, t;
    cin >> n;
    queue<int> q;
    for (int i = 0; i < n; i++) {
        cin >> t;
        q.push(t);
    }
    int j = 1;
    stack<int> s;
    vector<string> ans;
    while (!q.empty()) {
        if (s.empty()) {
            ans.push_back("+");
            s.push(j);
            j++;
        }
        if (s.top() > q.front()) {
            cout << "NO" << '\n';
            return 0;
        } else if (s.top() == q.front()) {
            ans.push_back("-");
            s.pop();
            q.pop();
            if (!q.empty() && s.empty()) {
                ans.push_back("+");
                s.push(j);
                j++;
            }
        } else {
            for (; j <= q.front(); j++) {
                ans.push_back("+");
                s.push(j);
            }
            if (s.top() == q.front()) {
                ans.push_back("-");
                s.pop();
                q.pop();
            }
        }
    }

    for (auto i = ans.begin(); i < ans.end(); i++) {
        cout << *i << '\n';
    }
    return 0;
}

나 같은 경우에는 문제를 이해하는데 너무 많은 시간이 걸렸기에 문제에 대한 설명을 남기고자 한다. 일단 컴퓨터는 1부터 차례대로 증가시키며 숫자를 넣을 수 있는 곳이 있다. 나는 그 곳을 위에서 stack으로 만들었다. 그리고 사용자에게 입력받은 숫자는 queue로 만들었는데, 위에서 스택에 숫자를 차례대로 넣으며 queue의 front에 있는 경우에는 이를 pop하는 식으로 만들었다.

말을 워낙 못해서 내가 다음 번에 이걸 봤을 때 이해할 수 있을지 모르겠다. 설명이랑 코드를 같이 보면 어떻게든 이해하겠지..?

좋은 웹페이지 즐겨찾기