백준 문제풀이/백준 Silver
BOJ 10866 - 덱 [C/C++
LKBaekjoon
2023. 10. 30. 16:41
반응형
10866번: 덱
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
문제 설명은 다음과 같다.
흔히 우리가 아는 Deque를 그냥 구현하라는,,, 간단한 문제였다.
편하게 <deque>를 include해서 문제를 풀었다.
그나마 생각해야 하는 부분은, empty일 때 조사 한 번 해서 0과 1중 적절한 값을 뱉어야 한다는 것.
그러니까, deque에 들어있는 size의 개수를 항상 tracking 하고 있으면 좋다는 것이다.
아래는 제출한 C++ 코드이다.
#include <iostream>
#include <algorithm>
#include <vector>
#include <deque>
using namespace std;
deque<int> stack;
int returnSomethingWithStack(string command, deque<int> ans){
if (command == "front") return ans.empty() ? -1 : ans.front();
if (command == "back") return ans.empty() ? -1 : ans.back();
else if (command == "pop_front") {
if (ans.empty()) {
return -1;
}
int a = stack.front();
stack.pop_front();
return a;
}
else if (command == "pop_back") {
if (ans.empty()) {
return -1;
}
int a = stack.back();
stack.pop_back();
return a;
}
else if (command == "size") return ans.size();
else if (command == "empty") return ans.empty() ? 1 : 0;
else {
return 0;
}
}
int main() {
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int command_num;
cin >> command_num;
cin.ignore();
for (int i=0;i<command_num;i++){
string command;
getline(cin, command, '\n');
string cmd1;
string cmd2;
cmd1 = command.substr(0, command.find(" "));
cmd2 = command.substr(command.find(" ") + 1, command.length());
if (cmd1 == "push_back") {
stack.push_back(stoi(cmd2));
}
else if (cmd1 == "push_front") {
stack.push_front(stoi(cmd2));
}
else {
cout << returnSomethingWithStack(command, stack) << '\n';
}
}
return 0;
}
반응형