목차

     

     


     

     

     

    [백준 1874번 C/C++] 스택 수열

     

    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


     

    해결전략

     

    Stack 사용

     

     


     

    코드

     

    #include <iostream>
    #include <stack>
    #include <vector>
    using namespace std;
    
    stack<int> st;
    vector<char> v;
    
    int main() {
        std::ios::sync_with_stdio(false);
        std::cin.tie(NULL);
        int n, input, num=0;
        cin >> n;
    
        st.push(num++);
        
        for(int i=0; i<n; i++){
            cin >> input;
    
            while(true){
                if (st.top() == input) break;
    
                if(st.top()>input){
                    cout << "NO";
                    return 0;
                }
                st.push(num++);
                v.push_back('+');
            }
            st.pop();
            v.push_back('-');    
        }
    
    	for(const auto& i : v)
    	{
            cout << i << "\n";
    	}
        
        return 0;
    }