Algorithm/Problem Solve

[백준 10866번] 덱

아네스 2020. 12. 14. 17:56
반응형

배열을 원형큐로 쓰는거 헤매가지고 좀 걸렸던것 같다.

#include <bits/stdc++.h>

using namespace std;

#define MAXSIZE 100000
typedef class _deque{
private:
    int ary[100000];
    int back;
    int front;
    int datasize;
public:
    _deque(){
        back = 1;
        front = 0;
        datasize =0;
    }
    void push_front(int a)
    {
        ary[front] = a;
        front = (front-1 + MAXSIZE) % MAXSIZE;
        datasize++;
    }
    void push_back(int a)
    {
        ary[back] = a;
        back = (back+1 +MAXSIZE)%MAXSIZE;
        datasize++;
    }
    void pop_front(){
        
        if(datasize ==0) cout << "-1\n";
        else{
            front = (front+1 +MAXSIZE) % MAXSIZE;
            cout <<ary[front] << '\n';
            datasize--;
        }
    }
    void pop_back(){
        
        if(datasize ==0) cout << "-1\n";
        else{
            back = (back-1 + MAXSIZE) %MAXSIZE;
            cout << ary[back] << '\n';
            datasize--;
        }
    }
    void size(){
        cout << datasize << '\n';
    }
    void empty(){
        if(datasize==0) cout <<"1\n";
        else{
            cout << "0\n";
        }

    }
    void _front(){
        if(datasize ==0) cout << "-1\n";
        else{
            int temp = (front+1+MAXSIZE)%MAXSIZE;
            cout << ary[temp] << '\n';
        }
        
    }
    void _back(){
        if(datasize ==0) cout << "-1\n";
        else{
            int temp = (back-1+MAXSIZE) %MAXSIZE;
            cout << ary[temp] << '\n';
        }
    }

}deq;
int main(void)
{
    ios::sync_with_stdio(false);
    cin.tie(NULL); cout.tie(NULL);
    int N;
    cin >> N;
    deq q;
    for(int i = 0; i< N; i++)
    {
        string s;
        cin >> s;
        if(s == "push_back"){
            int temp;
            cin>>temp;
            q.push_back(temp);
        }
        else if(s=="push_front")
        {
            int temp;
            cin >> temp;
            q.push_front(temp);
        }
        else if(s=="pop_front") q.pop_front();
        else if(s=="pop_back") q.pop_back();
        else if(s=="size") q.size();
        else if(s=="empty") q.empty();
        else if(s=="front") q._front();
        else if(s=="back") q._back();
        
    }
}
반응형