본문 바로가기

algorithm/Stack, Queue, Deque

[C++] BOJ 10828 스택

문제

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

 

10828번: 스택

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

www.acmicpc.net

코드

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

int n;
int main(){
	cin >> n;
	string str;
	stack<int> s;
	while (n--) {
		cin >> str;
		if (str == "push") {
			int num;
			cin >> num;
			s.push(num);
		}
		else if (str == "pop") {
			if (!s.empty()) {
				cout << s.top() << '\n';
				s.pop();
			}
			else
				cout << "-1\n";
		}
		else if (str == "size") {
			cout << s.size() << '\n';
		}
		else if (str == "empty") {
			if (s.empty())
				cout << "1\n";
			else
				cout << "0\n";
		}
		else if (str == "top") {
			if (s.empty())
				cout << "-1\n";
			else
				cout << s.top()<<'\n';
		}
	}
}

풀이방법

STL stack을 이용했다.

고민과정

너무 오랜만이라 stack 이용법을 잊었었다. STL을 쓰지 않고 직접 구현하라고 한다면 못했을지도 모르겠다.

'algorithm > Stack, Queue, Deque' 카테고리의 다른 글

[C++] BOJ 2346 풍선 터뜨리기  (0) 2021.07.09
[C++] BOJ 1918 후위 표기식  (0) 2021.05.21
[C++] BOJ 1158 요세푸스 문제  (0) 2021.05.21
[C++] BOJ 2161 카드1  (0) 2021.05.21
[C++] BOJ 10773 Zero That Out  (0) 2021.05.21