๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
Algorithm๐Ÿฐ/๋ฐฑ์ค€

[๋ฐฑ์ค€] 10828 stack

by Jouureee 2021. 2. 6.

๋ฌธ์ œ : 

www.acmicpc.net/problem/10828

 

 

10828๋ฒˆ: ์Šคํƒ

์ฒซ์งธ ์ค„์— ์ฃผ์–ด์ง€๋Š” ๋ช…๋ น์˜ ์ˆ˜ N (1 ≤ N ≤ 10,000)์ด ์ฃผ์–ด์ง„๋‹ค. ๋‘˜์งธ ์ค„๋ถ€ํ„ฐ N๊ฐœ์˜ ์ค„์—๋Š” ๋ช…๋ น์ด ํ•˜๋‚˜์”ฉ ์ฃผ์–ด์ง„๋‹ค. ์ฃผ์–ด์ง€๋Š” ์ •์ˆ˜๋Š” 1๋ณด๋‹ค ํฌ๊ฑฐ๋‚˜ ๊ฐ™๊ณ , 100,000๋ณด๋‹ค ์ž‘๊ฑฐ๋‚˜ ๊ฐ™๋‹ค. ๋ฌธ์ œ์— ๋‚˜์™€์žˆ์ง€

www.acmicpc.net

๋ถ„์„ : 

<stack> ์„ ์‚ฌ์šฉํ•˜์—ฌ ๋น„๊ต์  ์‰ฝ๊ฒŒ ํ’€ ์ˆ˜ ์žˆ์—ˆ๋˜ ๋ฌธ์ œ์˜€๋‹ค. ๋‹ค๋งŒ ์ฒ˜์Œ์œผ๋กœ segmentation fault ์ปดํŒŒ์ผ ์—๋Ÿฌ๊ฐ€ ๋–ด๋Š”๋ฐ top ๋ถ€๋ถ„์— empty ์กฐ๊ฑด์„ ๊ฒ€์‚ฌํ•˜์ง€ ์•Š์•„์„œ ๋‚œ ๋ฌธ์ œ์˜€๋‹ค. ์ •์˜๋œ ๋ฌธ์ œ๋ฅผ ์•ž์œผ๋ก  ๋” ์ž˜ ์ฝ์–ด์•ผ๊ฒ ๋‹ค. ๊ทธ๋ฆฌ๊ณ  ์ฒ˜์Œ์œผ๋กœ cin ์ด ๊ณต๋ฐฑ ๊ธฐ์ค€์œผ๋กœ ๋ถ„๋ฆฌํ•ด ์ฝ๋Š”๋‹ค๋Š” ์ ์„ ์•Œ๊ฒŒ ๋˜์—ˆ๋‹ค. ์ด๋ฅผ ์œ„ํ•ด getline ํ•จ์ˆ˜๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ํ–ˆ๊ณ  cin ๊ณผ getline์„ ๊ฒธ์šฉํ•ด์„œ ์“ฐ๋ฉด ์—๋Ÿฌ๊ฐ€ ๋‚  ์ˆ˜ ์žˆ๋Š”๋ฐ ์ด๋•Œ cin ์ฝ”๋“œ ๋’ค ignore ๋ฅผ ๋ถ™์—ฌ์ฃผ๋ฉด ํ•ด๊ฒฐ ๋œ๋‹ค๋Š” ์ ์„ ์•Œ๊ฒŒ ๋˜์—ˆ๋‹ค.

 

c++ ์ฝ”๋“œ :   

//
//  10828_stack.cpp
//  SOMA๐Ÿ‘ฉ๐Ÿป‍๐Ÿ’ป
//
//  Created by JoSoJeong on 2021/02/06.
//

#include <string>
#include <string.h>
#include <iostream>
#include <stack>

using namespace std;


int main(void){
    int n;
    cin >> n;
    string s;

    stack<int> arr;
    
    for(int i=0; i< n; i++){
        cin >> s;
        if(s == "push"){
            int num;
            cin >> num;
            arr.push(num);
        }else if(s == "top"){
            if(arr.empty()){
                cout << "-1" << endl;
            }else {
                cout << arr.top() << endl;
            }
        }else if(s == "size"){
            cout << arr.size() << endl;
        }else if(s == "empty"){
            if(arr.empty()){
                cout << "1" << endl;
            }else{
                cout << "0" << endl;
            }
            //cout << (arr.empty() ? 1 : 0) << endl;
        }else if(s == "pop"){
            if(arr.empty()){
                cout << "-1" << endl;
            }else{
                cout << arr.top() << endl;
                arr.pop();
            }
        }
    }
    return 0;
}

๋Œ“๊ธ€