공부/PS (백준)
[BOJ] 10866 덱 / C++
happyst
2023. 1. 14. 16:51
https://www.acmicpc.net/problem/10866
10866번: 덱
첫째 줄에 주어지는 명령의 수 N (1 ≤ N ≤ 10,000)이 주어진다. 둘째 줄부터 N개의 줄에는 명령이 하나씩 주어진다. 주어지는 정수는 1보다 크거나 같고, 100,000보다 작거나 같다. 문제에 나와있지
www.acmicpc.net
#include <iostream>
#include <string>
#define DEQUE_SIZE 10000
using namespace std;
int N; // 명령의 수 (1<= <= 10000)
string cmd;
int input_data;
int front_ptr = 0, back_ptr = 0;
int deque[DEQUE_SIZE] = { 0, }; // index: 0 ~ 9999
int size() {
return (front_ptr - back_ptr + DEQUE_SIZE) % DEQUE_SIZE;
}
int empty() {
if (front_ptr == back_ptr) return 1;
else return 0;
}
void push_front(int num) {
if (size() != DEQUE_SIZE) { // NOT FULL
deque[front_ptr] = num;
front_ptr = (front_ptr + 1) % DEQUE_SIZE;
}
}
void push_back(int num) {
if (size() != DEQUE_SIZE) { // NOT FULL
back_ptr = (back_ptr - 1 + DEQUE_SIZE) % DEQUE_SIZE;
deque[back_ptr] = num;
}
}
int pop_front() {
if (empty()) return -1;
int num = deque[(front_ptr - 1 + DEQUE_SIZE) % DEQUE_SIZE];
front_ptr = (front_ptr - 1 + DEQUE_SIZE) % DEQUE_SIZE;
return num;
}
int pop_back() {
if (empty()) return -1;
int num = deque[back_ptr];
back_ptr = (back_ptr + 1) % DEQUE_SIZE;
return num;
}
int front() {
if (empty()) return -1;
else return deque[(front_ptr - 1 + DEQUE_SIZE) % DEQUE_SIZE];
}
int back() {
if (empty()) return -1;
else return deque[back_ptr];
}
int main(void)
{
cin >> N;
while (N--) {
cin >> cmd;
if (cmd == "push_front") {
cin >> input_data;
push_front(input_data);
}
else if (cmd == "push_back") {
cin >> input_data;
push_back(input_data);
}
else if (cmd == "pop_front") {
int num = pop_front();
cout << num << "\n";
}
else if (cmd == "pop_back") {
int num = pop_back();
cout << num << "\n";
}
else if (cmd == "size") {
int deque_size = size();
cout << deque_size << "\n";
}
else if (cmd == "empty") {
int is_empty = empty();
cout << is_empty << "\n";
}
else if (cmd == "front") {
int num = front();
cout << num << "\n";
}
else if (cmd == "back") {
int num = back();
cout << num << "\n";
}
}
return 0;
}
머리 터지는줄 알았네...
원형큐라고 생각하고 그림 그려가면서 했더니 이해 됨