02-线性结构4. Pop Sequence(25)

02-线性结构4. Pop Sequence(25)_第1张图片

题目的意思:
栈的大小M,输入序列的长度N(默认序列即为1,2,3…,N),入栈出栈的顺序不定。有K个测试序列,判断每一个测试序列是否是可能的出栈顺序。
核心:从出栈顺序推测入栈顺序

关键点:当看到pop t时,那么一定要先push 1,2,3…t-1,t,即要先将小于等于**t的数都push入栈才能pop t。这个过程中检查**pop的次数是否等于N以及入栈的数目是否大于栈的容量M

#include
#include
#include
#include
#include

using namespace std;
int M,N,K;
int check_stack(vector<int> &v){
    stack<int> sta;
    sta.push(0);    //dummy element, as sential
    int cap = M + 1;    //stack capacity
    int idx = 0;        //index of vector v
    int num = 1;        //to push to stack
    while(idx != N){
        while(v[idx]>sta.top()&&sta.size()if(v[idx]==sta.top()){
            sta.pop();
            idx++;
        }
        else //sta.size>=cap; idx>N
            return 0;   //false
    }
    return 1;   //true
}
int main(){
    //int M,N,K;
    cin>>M>>N>>K;
    vector<int> vec(N,0);   //N pop number
    for(int i = 0; i!=K; ++i){
        //input to vec
        copy_n(istream_iterator<int>(cin),N,vec.begin());
        cout << (check_stack(vec)?"YES":"NO")<

02-线性结构4. Pop Sequence(25)_第2张图片
语言技巧
copy_n(istream_iterator(cin),N,vec.begin());

当然也可以自己用c,写一下栈的操作,速度上会快不少

#include
#include

#define MaxSize 1000
//Stack implement with array
typedef struct node{
        int Data[MaxSize];
        int cap;
        int top;        //size = top+1
}Stack;

int M,N,K;
Stack *CreateStack(){
        Stack *PtrS = (Stack*)malloc(sizeof(struct node));
        PtrS->cap = MaxSize;
        PtrS->top = -1;
        return PtrS;
}

void Push(Stack *PtrS, int ele){
        if(PtrS->top == PtrS->cap-1){
                printf("FULL");
                return;
        }
        PtrS->top++;
        PtrS->Data[PtrS->top]=ele;
}

int top(Stack *PtrS){
        return PtrS->Data[PtrS->top];
}

void Pop(Stack *PtrS){
        if(PtrS->top==-1){
                printf("Empty");
                return;
        }
        PtrS->top--;
}

int check_stack(int v[]){
        int new_cap = M+1;
        Stack *ps = CreateStack();
        Push(ps,0);     //dummy element
        int idx = 0;    //index of v
        int num=1;      //to put to stack
        while(idx!=N){
                while(top(ps)top+1)if(top(ps)==v[idx]){
                        Pop(ps);
                        idx++;
                }
                else
                        return 0;       //false
        }
        return 1;

}

int main(){
        //输入
        scanf("%d %d %d",&M,&N,&K);
        int *v = (int *)malloc(sizeof(int)*N);
        int i;
        for(;K!=0;--K){
                for(i = 0; i!= N; ++i)
                        scanf("%d",v+i);
                if(check_stack(v))
                        printf("YES\n");
                else
                        printf("NO\n");
        }
        return 0;
}

02-线性结构4. Pop Sequence(25)_第3张图片

你可能感兴趣的:(PAT-MOOC-DS)