알고리즘 문제

백준 - 10828번 스택 (C++)

als982001 2023. 3. 27. 22:12

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

 

10828번: 스택

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

www.acmicpc.net

 이번 문제는 몇 가지 스택에 관한 명령어가 주어졌을 때, 각 명령어들에 대한 결과를 출력하는 문제이다. 난이도를 보면 알 수 있듯, 어려운 문제는 아니지만 스택이라는 개념을 알 수 있는 좋은 문제라 생각해 다시 한 번 풀어보았다. 스택이란 간단히 말해 마지막에 들어온 것이 가장 먼저 나가는 구조이다. 위의 사진이나 프링글스 통과 같은 구조를 생각하면 된다. 그렇기에 명령어가 push 숫자라면, 스택에 숫자를 넣고 명령어가 pop이라면 스택에서 가장 마지막에 넣은 숫자를 빼내면 된다. 예를 들어, 스택을 vector를 이용하여 구현하였다면 가장 마지막 숫자를 빼내면 될 것이다.

 그런데 C++에는 stack에 관한 라이브러리가 이미 존재하기 때문에 이를 이용하여 문제를 풀었다. 그렇지만 스택을 직접 구현해보는 것도 좋을 것이라 생각한다.

 

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <algorithm>
#include <queue>
#include <memory.h>
#include <deque>
#include <cmath>
#include <stack>
#include <cstring>
#include <typeinfo>
#include <iomanip>
#include <limits.h> 
#include <map>
#pragma warning(disable:4996)

using namespace std;

#define PUSH "push"
#define POP "pop"
#define TOP "top"
#define SIZE "size"
#define EMPTY "empty"

int N;
string input;
stack<int> stk;
vector<int> answer;

int main()
{
	ios_base::sync_with_stdio(false);
	std::cin.tie(NULL);
	std::cout.tie(NULL);

	cin >> N;
	cin.ignore();

	for (int i = 0; i < N; ++i)
	{
		cout << N << "번째 중, " << i + 1 << "번째 명령 => ";
		getline(cin, input);

		istringstream command(input);
		string cmd, strNum;
		
		command >> cmd >> strNum;

		if (cmd == PUSH)
		{
			int num = stoi(strNum);
			stk.push(num);
		}
		else if (cmd == POP)
		{
			int num;

			if (stk.empty())
				num = -1;
			else
			{
				num = stk.top();
				stk.pop();
			}

			answer.push_back(num);
		}
		else if (cmd == SIZE)
		{
			answer.push_back(stk.size());
		}
		else if (cmd == EMPTY)
		{
			int isEmpty = stk.empty() ? 1 : 0;
			answer.push_back(isEmpty);
		}
		else if (cmd == TOP)
		{
			int num = stk.empty() ? -1 : stk.top();
			answer.push_back(num);
		}
	}

	for (int i = 0; i < answer.size(); ++i)
		cout << answer[i] << endl;

    return 0;
}