題意:

給你一些指令以及數字,1是輸入數字,2是輸出數字;問說這種輸出方法會屬於哪種資料結構(stack,queue,priority queue)或是不可能有這種情況(impossible)或是還有多種可能(not sure)

 

解法:

直接開三種資料結構,都丟進去,當拿出時判斷哪種資料結構不符合就去掉,最後看是哪種狀況

 

程式碼:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int q[1234];
int s[1234];
int h[1234];
int qS,qE;
int sNum;
int hNum;
int n;
int key[3];

void insertQ(int num){
    q[qE++] = num;
}
void insertS(int num){
    s[++sNum] = num;
}
void insertPQ(int num){
    int now = ++hNum;
    while(now>1){
        if(h[now/2] <num){
            h[now] = h[now/2];
            now/=2;
        }else break;
    }
    h[now] = num;
}
int popQ(){
    if(qS == qE)return -10000000;
    return q[qS++];
}
int popS(){
    if(sNum<=0)return  -10000000;
    return s[sNum--];
}
int popPQ(){
    if(hNum<=0)return  -10000000;
    int tmp = h[1];
    int now = 1,next = 2;
    hNum--;
    while(next<=hNum){
        if(next<hNum && h[next+1] > h[next])++next;
        if(h[next] > h[hNum+1]){
            h[now] = h[next];
            now = next;
            next = now*2;
        }else break;
    }
    h[now] = h[hNum+1];
    return tmp;
}

int main(){
    int a,b;
    int pop;
    while(scanf("%d",&n)!=EOF){
        memset(key,0,sizeof(key));
        qS = qE = sNum = hNum = 0;
        while(n--){
            scanf("%d %d",&a,&b);
            if(a==1){
                insertQ(b);
                insertS(b);
                insertPQ(b);
            }else {
                pop = popQ();
                if(pop != b)key[0] = 1;
                pop = popS();
                if(pop != b)key[1] = 1;
                pop = popPQ();
                if(pop != b)key[2] = 1;
            }
        }
        if(key[0]+key[1]+key[2]==3)puts("impossible");
        else if(key[0]+key[1]+key[2]<2)puts("not sure");
        else {
            if(!key[0])puts("queue");
            if(!key[1])puts("stack");
            if(!key[2])puts("priority queue");
        }
    }
    return 0;
}

arrow
arrow
    全站熱搜

    alan790712 發表在 痞客邦 留言(0) 人氣()