알고리즘/백준(BOJ)

백준 18258 큐2

오뚜깅 2021. 2. 3. 18:34
반응형

STL에서 제공하는 <queue>를 사용하면 간단하게 문자열 비교를 통하여서 문제를 풀 수 있다.

이 문제를 풀면서 한 가지 유의했던 점은 시간인데, 기존에 시간을 절약하기 위해서 ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); 를 사용하였는데 이 문제는 이 것으로는 충분하지 않았다.

 

놓치고 있었던 부분 중 하나는 출력해줄 때 줄바꿈 연산자인 endl 를 사용하면 속도가 느려진다는 점이다.

또 하나는 if 문을 연달아 사용하는 것이었는데, 안좋은 습관 중 하나가 if~ else if 문을 사용하지 않고 if 문만 사용했다는 점이다. 이 부분도 실수하지 말아야할 부분 중 하나다.

#include <iostream>
#include <queue>

using namespace std;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    
    int N, tempInt;
    cin >> N;

    queue<int> q;
    string temp;
    for(int i = 0; i < N; i++){
        cin >> temp;
        if(temp == "push"){
            cin >> tempInt;
            q.push(tempInt);
        }
        else if(temp == "pop"){
            if(q.empty())
                cout << "-1\n";
            else
            {
                cout << q.front() << "\n";
                q.pop();
            }
        }
        else if(temp == "size"){
            cout << q.size() << "\n";
        }
        else if(temp == "empty"){
            if(q.empty())
                cout << "1\n";
            else{
                cout << "0\n";
            }
        }
        else if(temp == "front"){
            if(q.empty())
                cout << "-1\n";
            else
            {
                cout << q.front() << "\n";
            }
        }
        else if(temp == "back"){
            if(q.empty())
                cout << "-1\n";
            else
            {
                cout << q.back() << "\n";
            }
        }
    }

    return 0;
}
반응형