알고리즘

백준 10845 큐 [C++]

NUMERO_K 2018. 11. 25. 21:59


문제 링크 : https://www.acmicpc.net/problem/10845


소스코드


#include <iostream>
#include <queue>
#include <string>
using namespace std;
int main() {
    queue<int> q;
    int n;
    cin >> n;
    cin.ignore();
    for (int i = 0; i < n; ++i) {
        string order;
        getline(cin, order);
        if (order == "pop") {
            if (q.empty()) cout << -1 << endl;
            else {
                cout << q.front() << endl;
                q.pop();
            }
        }
        else if (order == "size") {
            cout << q.size() << endl;
        }
        else if (order == "empty") {
            if (q.empty()) cout << 1 << endl;
            else cout << 0 << endl;
        }
        else if (order == "front") {
            if (q.empty()) cout << -1 << endl;
            else
                cout << q.front() << endl;
        }
        else if (order == "back") {
            if (q.empty()) cout << -1 << endl;
            else
                cout << q.back() << endl;
        }
        else {
            order = order.erase(0, 5);
            int x = stoi(order);
            q.push(x);
        }
    }
}


큐는 스택과 다르게 먼저 들어온 데이터가 먼저나가는 자료 구조입니다.


C++에서 제공하는 STL을 사용하면 쉽게 큐를 사용하실 수 있습니다.


큐 STL 사용법 : http://www.dreamy.pe.kr/zbxe/CodeClip/3768930