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

seul·2020년 10월 8일
0

백준

목록 보기
6/7
#include<bits/stdc++.h>
using namespace std;

int main()
{
    stack<int> s;
    vector<int> v;
    vector<char> answer;
    int isNo = 0;
    int n;
    cin >> n;
    for(int i=0; i<n; i++) {
        int num;
        cin >> num;
        v.push_back(num);
    }

    for(int i=0;i<n;i++) {
        int lastPush;
        
        if(s.empty()) {
            for(int j = i; j < v.at(i); j++) {
                s.push(j+1);
                answer.push_back('+');
                lastPush = j+1;
            }
            if(s.top() == v.at(i)) { 
                answer.push_back('-');
                s.pop();
            }
        }

        else if(lastPush > v.at(i) && s.top() < v.at(i)) {
            isNo = 1;
            break;
        }

        else if(s.top() < v.at(i) && i > 0) {
            for(int j = lastPush; j < v.at(i); j++) {
                s.push(j+1);
                answer.push_back('+');
                lastPush = j+1;
            }
            if(s.top() == v.at(i)) { 
                answer.push_back('-');
                s.pop();
            }
        }

        else if (s.top() == v.at(i)) {
            answer.push_back('-');
            s.pop();
        }

        else if(s.top() > v.at(i)) {
            while(s.top()!=v.at(i)) {
                answer.push_back('-');
                s.pop();
            }
        }
    }

    if(isNo == 1) cout << "NO\n";
    else 
        for(int i = 0; i<answer.size(); i++) cout <<answer.at(i) << "\n";
   
    return 0;
}

철저하게 조건들 하나하나 나눠서 생각했던 것 같다.. 완전 개차반으로 짜서 틀릴줄 알았는데 맞아서 신기했음
다 풀고 다른 사람들 풀이 보는데, No 출력 조건 어렵게 생각 안해도 되었음!! 그냥 stack이 empty가 아니라면 No 출력하면 그만...😞

profile
무한삽질로그

0개의 댓글