코딩테스트/Baekjoon

[백준 #10828] 스택 (C++)

동띵 2021. 8. 17. 15:23

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

 

10828번: 스택

첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지

www.acmicpc.net

 

stack은 C++ STL에 정의되어 있기 때문에

<stack>이라는 헤더 파일을 include 하여 풀면 쉽다.

 

여기서 주의할 점은 문제에 나온 pop 명령어가 스택에서 가장 위에 있는 정수를 빼고

그 수를 출력한다는 것이다.

 

pop()을 사용하면 스택의 top 데이터를 삭제할 뿐 출력하지 않는다.

따라서 문제 속 pop 명령어대로 실행하려면 top()을 사용해 최상위 데이터를 반환한 다음

pop()을 하여 그 데이터를 삭제해야 한다.

 

#include <iostream>
#include <stack>
using namespace std;
stack<int> s;

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

	int n, num;
	string command;

	cin >> n;
	for (int i = 0; i < n; i++) {
		cin >> command;

		if (command == "push") {
			cin >> num;
			s.push(num);
		}
		else if (command == "pop") {
			if (s.empty()) cout << -1 << "\n";
			else {
				cout << s.top() << "\n";
				s.pop();
			}
		}
		else if (command == "size") {
			cout << s.size() << "\n";
		}
		else if (command == "empty") {
			cout << s.empty() << "\n";
		}
		else if (command == "top") {
			if (s.empty()) cout << -1 << "\n";
			else {
				cout << s.top() << "\n";
			}
		}
		else break;
	}
	return 0;
}