백준 10845 (C++) 큐
728x90
SMALL

기본적인 구현 문제였다.

이런 문제는 c++의 stl인 queue를 사용해도 되지만,

자료구조 학습 기간이 길지 않은 초보자라면 직접 구현해보길 권장한다.

 

 

front 와 back을 증가시키기만 하는 linear queue를 구현해도

주어진 input이 배열의 범위를 넘어가지 않아서 circular queue가 필요하지 않은 것 같다.

 

circular queue는 modulo를 사용하면 된다.

 

 

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

 

10845번: 큐

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

www.acmicpc.net

 

 

 

SMALL
#include <iostream>
#include <algorithm>
using namespace std;
using ll = long long;
const int MAX = 100001;
int queue[MAX];
int front = 0;
int back = 0;
int n;
int size(); // pop()에서 size()함수 사용을 위한 선언
void push(int x) {
    queue[back] = x;
    back++;
}
void pop() {
    if (size() == 0) { // 큐가 비어있다면
        cout << "-1\n";
        return;
    }
    cout << queue[front] << '\n';
    front++;
}
int size() {
    return back - front;
}
int main(void) {
    ios_base::sync_with_stdio(false);
    cin.tie(0); cout.tie(0);
    cin >> n;
    while (n--) {
        string cmd;
        cin >> cmd;
        if (cmd == "push") {
            int a;
            cin >> a;
            push(a);
        }
        else if (cmd == "pop") {
            pop();
        }
        else if (cmd == "size") {
            cout << size() << '\n';
        }
        else if (cmd == "empty") {
            if (size() == 0) {
                cout << "1\n";
            }
            else cout << "0\n";
        }
        else if (cmd == "front") {
            if (size() == 0) { // 큐가 비어있다면
                cout << "-1\n";
            }
            else cout << queue[front] <<'\n';
        }
        else { // back이 cmd일 때
            if (size() == 0) {
                cout << "-1\n";
            }
            else cout << queue[back-1] <<'\n';
        }
    }
    return 0;
}

 

 

 

 

 

 

 

728x90
LIST