๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm ๐Ÿง‘๐Ÿป‍๐Ÿ’ป/๋ฐฑ์ค€(BOJ)

[๋ฐฑ์ค€,c++] 1874๋ฒˆ - ์Šคํƒ ์ˆ˜์—ด

by ์•ˆ์ฃผํ˜• 2022. 3. 9.

๋ฌธ์ œ

 

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 <vector>

using namespace std;

int main(){
    ios_base::sync_with_stdio(false);
    cin.tie(0);
    
    int N; cin>>N;
    stack<int>st;
    vector<char> ans;
    
    int curr = 0;
    while(N--){
        int num; cin>>num;
        
        if(st.empty()){
            if(curr>num){
                cout<<"NO";
                return 0;
            }
            int first = curr;
            for(int i=0; i<abs(num-first); i++){
                ans.push_back('+');
                st.push(++curr);
            }
            ans.push_back('-');
            st.pop();
        }
        
        else if(st.top()==num){
            ans.push_back('-');
            st.pop();
        }
        
        else if(st.top()>num){
            while(true){
                if(st.top()==num) break;
                ans.push_back('-');
                st.pop();
            }
        }
        else if(st.top()<num){
            if(curr>num){
                cout<<"NO";
                return 0;
            }
            while(true){
                if(st.top()==num){
                    ans.push_back('-');
                    st.pop();
                    break;
                }
                ans.push_back('+');
                st.push(++curr);
            }
        }
    }
    for(char c: ans) cout<<c<<'\n';
}

 

ํ’€์ด

์ฝ”๋“œ ๊ตฌํ˜„ ์ž์ฒด๋Š” ์–ด๋ ต์ง€ ์•Š์œผ๋‚˜ ์ด ๋ฌธ์ œ๋ฅผ ์ฒ˜์Œ ๋ณด์•˜์„ ๋•Œ ๋ฌธ์ œ ์ž์ฒด๊ฐ€ ์ดํ•ด๊ฐ€ ๊ฐ€์ง€๋ฅผ ์•Š์•˜์Šต๋‹ˆ๋‹ค. ์ž…์ถœ๋ ฅ์„ ๋ณด๊ณ  ๋Œ€์ถฉ ์˜ˆ์ƒ์€ ํ•ด์„œ ํ’€์–ด๋ณด์•˜์ง€๋งŒ ๋ฌด์–ธ๊ฐ€ ์ž˜๋ชป๋˜์—ˆ๋Š”์ง€ ์ฑ„์ ํ–ˆ์„ ๋•Œ๋Š” ์˜ค๋‹ต์ด ๋–ด๊ณ  ๊ทธ๋ ‡๊ฒŒ ๋ฏธ์ณ๊ฐ€๋˜ ๋„์ค‘ ์งˆ๋ฌธ ๊ฒŒ์‹œํŒ์—์„œ ์•„๋ž˜ ๋ฌธ์ œ ์„ค๋ช… ์˜์ƒ์„ ์ฐพ์•„์„œ ๋ณด๊ฒŒ ๋˜์—ˆ์Šต๋‹ˆ๋‹ค.

์œ„ ์˜์ƒ์ด ์—†์—ˆ์œผ๋ฉด ์•„์ง๋„ ๋ฌธ์ œ ์ดํ•ด์กฐ์ฐจ ๋ชปํ–ˆ์„ ๊ฒƒ์ž…๋‹ˆ๋‹ค.(์ œ์ž‘์ž ๋ถ„๊ป˜ ๊ฐ์‚ฌ๋“œ๋ฆฝ๋‹ˆ๋‹ค.)  ๋ฌธ์ œ ์ดํ•ด๊ฐ€ ๊ฐ€์ง€ ์•Š์œผ์‹  ๋ถ„๋“ค์€ ํ•œ๋ฒˆ ์‹œ์ฒญํ•˜์‹œ๋ฉด ์ดํ•ด๊ฐ€ ๋ฐ”๋กœ ๋  ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.

๋Œ“๊ธ€