카테고리 없음
백준 - 10845번 큐 (C++)
als982001
2023. 3. 28. 16:13
https://www.acmicpc.net/problem/10845
10845번: 큐
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
이번 문제는 큐에 관한 명령어들이 주어졌을 때, 각 명령어들에 대한 결과를 출력하는 문제이다. 이 문제릂 풀기 위해서는 큐가 뭔지를 알아야 한다. 큐란 간단히 말해서 가장 먼저 들어간 데이터가 가장 먼저 나가는 자료구조이다. 예를 들자면 위의 사진같이 가장 먼저 줄을 선 사람이 가장 먼저 나가는 것이라 할 수 있다. 문제에서 주어지는 명령어는 push, pop, size, empty, front, back이 있다. 만약, 큐를 직접 구현한다면 앞에서 말했듯 push는 주어진 숫자를 가장 뒤에 넣고 pop은 가장 앞의 숫자를 빼면 된다. 하지만 C++에는 이미 큐에 관한 라이브러리가 있기에 이 문제는 이를 이용하여 풀었다.
#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 SIZE "size"
#define EMPTY "empty"
#define FRONT "front"
#define BACK "back"
int N;
string input;
queue<int> q;
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)
{
getline(cin, input);
istringstream command(input);
string cmd, strNum;
command >> cmd >> strNum;
if (cmd == PUSH)
{
int num = stoi(strNum);
q.push(num);
}
else if (cmd == POP)
{
if (q.empty())
answer.push_back(-1);
else
{
int num = q.front();
q.pop();
answer.push_back(num);
}
}
else if (cmd == SIZE)
{
answer.push_back(q.size());
}
else if (cmd == EMPTY)
{
int isEmpty = q.empty() ? 1 : 0;
answer.push_back(isEmpty);
}
else if (cmd == FRONT)
{
if (q.empty())
answer.push_back(-1);
else
answer.push_back(q.front());
}
else if (cmd == BACK)
{
if (q.empty())
answer.push_back(-1);
else
answer.push_back(q.back());
}
}
for (int i = 0; i < answer.size(); ++i)
cout << answer[i] << endl;
return 0;
}