알고리즘

C++ 알고리즘 - 백준 10828 스택

마루설아 2024. 12. 31. 20:48

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

 

#include <bits/stdc++.h>
#define endl "\n"

using namespace std;

int main(void) {
	// C++ Init
	ios::sync_with_stdio(false);
	cin.tie(NULL);

	int input;
	int num;
	string str;
	stack<int> st;
	cin >> input;
	cin.ignore();

	for (int i = 0; i < input; i++) {
		getline(cin, str);

		if (str == "top") {
			if (st.empty()) cout << -1 << endl;
			else cout << st.top() << endl;
		}

		else if (str == "pop") {
			if (st.empty()) cout << -1 << endl;
			else {
				num = st.top();
				st.pop();
				cout << num << endl;
			}
		}

		else if (str == "size") {
			cout << st.size() << endl;
		}

		else if (str == "empty") {
			cout << st.empty() << endl;
		}

		else if (str.find("push") != -1) {
			string number = str.erase(0, 5);
			num = stoi(number);
			st.push(num);
		}
	}
}