10845번: 큐
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지 ��
www.acmicpc.net
[문제 풀이]
STL을 이용한 것과 직접 구현한 것 두 가지로 문제를 풀어보았습니다.
이 문제는 단순히 큐을 구현하는 것이므로 설명은 생략하겠습니다.
코드는 STL을 이용한 코드와 직접 구현한 코드 두 가지를 적어 놓은 것입니다.
[STL 코드]
#include<iostream>
#include<queue>
#include<string>
using namespace std;
int N;
queue<int> que;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> N;
string exec;
for (int i = 0; i < N; i++) {
cin >> exec;
if (exec == "push") { //push
int temp;
cin >> temp;
que.push(temp);
}
else if (exec == "pop") { //pop
if (que.empty())
cout << -1 << endl;
else {
cout << que.front() << endl;
que.pop();
}
}
else if (exec == "size") { //size
cout << que.size() << endl;
}
else if (exec == "empty") { //empty
if (que.empty())
cout << 1 << endl;
else
cout << 0 << endl;
}
else if (exec == "front") { //top
if (que.empty())
cout << -1 << endl;
else
cout << que.front() << endl;
}
else if (exec == "back") { //top
if (que.empty())
cout << -1 << endl;
else
cout << que.back() << endl;
}
}
return 0;
}
[직접 구현 코드]
#include<iostream>
#include<string>
using namespace std;
int arr[10000] = { 0, };
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
int n; cin >> n;
int pre_idx = -1, post_idx = -1;
for (int i = 0; i < n; i++) {
string str;
cin >> str;
if (str == "push") {
int x; cin >> x;
post_idx++;
arr[post_idx] = x;
}
else if (str == "pop") {
if (pre_idx == post_idx)
cout << "-1" << endl;
else {
pre_idx++;
cout << arr[pre_idx] << endl;
arr[pre_idx] = 0;
}
}
else if (str == "size") {
cout << post_idx - pre_idx << endl;
}
else if (str == "empty") {
if (pre_idx == post_idx)
cout << 1 << endl;
else
cout << 0 << endl;
}
else if (str == "front") {
if (pre_idx == post_idx)
cout << -1 << endl;
else
cout << arr[pre_idx + 1] << endl;
}
else if (str == "back") {
if (pre_idx == post_idx)
cout << -1 << endl;
else
cout << arr[post_idx] << endl;
}
}
return 0;
}
'algorithm > BOJ' 카테고리의 다른 글
백준 1927_최소 힙(C++) (0) | 2020.10.18 |
---|---|
백준 11279_최대 힙(C++) (0) | 2020.10.18 |
백준 10828_스택(C++) (0) | 2020.10.17 |
백준 7453_합이 0인 네 정수(C++) (0) | 2020.10.15 |
백준 2143_두 배열의 합(C++) (0) | 2020.10.10 |