백준 문제 풀이 & C++ 공부
백준 10828번 C++
daisy0461
2021. 8. 19. 23:39
https://www.acmicpc.net/problem/10828
10828번: 스택
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
이번 문제는 c++로 풀면 간단하게 stack을 활용할 수 있다면 쉽게 풀 수 있는 문제입니다.
문제를 풀면서 큰 어려움은 없었습니다.
다들 쉽게 풀 수 있을 것이라고 생각합니다.
#include <iostream>
#include<algorithm>
#include<vector>
#include<stack>
using namespace std;
int main(int argc, const char* argv[]) {
int n; //명령 수
stack<int> orderStack;
cin >> n;
for (int i = 0; i < n; i++) {
string a;
cin >> a;
if (a == "push") {
int number;
cin >> number;
orderStack.push(number);
}
else if(a == "top")
{
if (orderStack.empty()) { //stack이 비어있다면 -1 출력
cout << "-1" << endl;
}
else
{
cout << orderStack.top() << endl;
}
}
else if (a == "size") {
cout << orderStack.size() << endl;
}
else if (a == "empty") {
if (orderStack.empty()) {
cout << "1" << endl;
}
else {
cout << "0" << endl;
}
}
else if (a == "pop") {
if (orderStack.empty()) {
cout << "-1" << endl;
}
else {
int popNumber;
popNumber = orderStack.top();
cout << popNumber << endl;
orderStack.pop();
}
}
}
}