본문 바로가기

백준/C++

[C++] 백준 28278번 - 스택 2

728x90

 

문제 28278번

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

 

 

이번에는 문제에 나온대로 구현하면 된다. 스택을 만들고 값을 넣을 때는 push(), 스택 안에 있는 값을 뺄 때는 pop(), 스택의 맨 위는 top(), 비어있는지 확인하는 것은 empty()이다. 여기서 비어있다면 1, 아니면 0이 반환된다.

 

 

cin, cout으로 하면 시간 초과가 되기 때문에 scanf와 printf를 사용하였다.

 

 

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

int main() {
	stack <int> st;
	int N;
	scanf("%d", &N);
	
	for (int i = 0; i < N; i++) {
		int command = 0;
		scanf("%d", &command);
		if (command == 1) {
			int x = 0;
			scanf("%d", &x);
			st.push(x);
		}
		else if (command == 2) {
			if (st.empty()) {
				printf("-1\n");
			}
			else {
				printf("%d\n", st.top());
				st.pop();
			}
		}
		else if (command == 3) {
			printf("%d\n", st.size());
		}
		else if (command == 4) {
			if (st.empty()) {
				printf("1\n");
			}
			else {
				printf("0\n");
			}
		}
		else if (command == 5) {
			if (st.empty()) {
				printf("-1\n");
			}
			else {
				printf("%d\n", st.top());
			}
		}
	}

	return 0;
}

 

 

728x90