포스트

백준 10828

push·pop·size·empty·top 명령을 처리하는 스택 구현 — STL stack 사용

출처: https://www.acmicpc.net/problem/10828

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// 백준 10828
// https://www.acmicpc.net/problem/10828


#include <iostream>
#include <stack>
#include <string>
using namespace std;

int main() {
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);

    int n;
    cin >> n;

    stack<int> s;
    string cmd;

    for(int i=0; i<n; i++){
        cin >> cmd;
        if(cmd == "push"){
            int num;
            cin >> num;
            s.push(num);
        }
        else if(cmd == "pop"){
            if(s.empty())
                cout << "-1\n";
            else{
                cout << s.top() << "\n";
                s.pop();
            }
        }
        else if(cmd == "size"){
            cout << s.size() << "\n";
        }
        else if(cmd == "empty"){
            cout << s.empty() << "\n";
        }
        else if(cmd == "top"){
            if(s.empty())
                cout << "-1\n";
            else
                cout << s.top() << "\n";
        }
    }

    return 0;
}

핵심 요약 — STL stackpop()은 값을 돌려주지 않으므로 top()으로 읽은 뒤 pop()으로 제거한다. pop·top 명령은 empty()로 빈 스택 여부를 먼저 확인해 -1을 출력했다.

이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.