์ƒ์„ธ ์ปจํ…์ธ 

๋ณธ๋ฌธ ์ œ๋ชฉ

[๋ฐฑ์ค€(BOJ)] 10828๋ฒˆ: ์Šคํƒ (์Šคํƒ, C++)

PROGRAMMING/Algorithm

by koharin 2021. 8. 7. 15:08

๋ณธ๋ฌธ

728x90
๋ฐ˜์‘ํ˜•

๐Ÿ“„ ๋ฌธ์ œํ’€์ด ๊ณผ์ •


C++ STL stack ์„ ์‚ฌ์šฉํ•ด์„œ ์Šคํƒ์„ ๊ตฌํ˜„ํ–ˆ๋‹ค.

์ž…๋ ฅ ์‹œ push์—์„œ whitespace ๋’ค์— ์ˆซ์ž๊ฐ€ ์˜ค๊ธฐ ๋•Œ๋ฌธ์—  getline()์œผ๋กœ ์ž…๋ ฅ๋ฐ›์•˜๊ณ , std::cin >> std::ws ์œผ๋กœ newline์„ ๋ฌด์‹œํ•˜๊ณ  ์—”ํ„ฐ ์‹œ ๋‹ค์Œ ์ŠคํŠธ๋ง์„ ์ž…๋ ฅ๋ฐ›๋„๋ก ํ–ˆ๋‹ค.

switch๋ฌธ์—์„œ p ๋ฌธ์ž์ธ ๊ฒฝ์šฐ์—์„œ ๋‘ ๋ฒˆ์งธ ๋ฌธ์ž๋กœ push์™€ pop ๊ตฌ๋ถ„ํ–ˆ๋‹ค.

์Šคํƒ์ด ๋น„์–ด์žˆ๋Š” ์—ฌ๋ถ€์— ๋Œ€ํ•ด์„œ๋Š” ์‚ผํ•ญ์—ฐ์‚ฐ์ž๋ฅผ ์‚ฌ์šฉํ•ด์„œ ์ถœ๋ ฅํ–ˆ๋‹ค.

 

 

๐Ÿ’ป ์ฝ”๋“œ


#include <bits/stdc++.h>
using namespace std;

int main(){
    stack<int> s;
    int N;
    scanf("%d", &N); // N: # of instructions
    
    for(int i=0; i<N; i++){
        string str;
        getline(cin >> std::ws, str);
       
        switch(str[0]){
            case 'p':
            {
                if(str[1] == 'u') s.push(stoi(str.substr(str.find(" ")+1)));
                else{
                    if(s.empty()) cout << -1 << endl;
                    else{
                        cout << s.top() << endl;
                        s.pop();
                    }	
                }
            }
            break;
            case 's':
            cout << s.size() << endl;
            break;
            case 'e':
            cout << (s.empty() ? 1 : 0) << endl;
            break;
            case 't':
            cout << (s.empty() ? -1 : s.top()) << endl;
            break;
        }
    }
    
}

 

 

๐Ÿ–จ ์ œ์ถœ๊ฒฐ๊ณผ


728x90
๋ฐ˜์‘ํ˜•

๊ด€๋ จ๊ธ€ ๋”๋ณด๊ธฐ