Pop Sequence 题解 代码 心得

Pop Sequence

题面

Given a stack which can keep M numbers at most. Push N numbers in the order of 1, 2, 3, ..., N and pop randomly. You are supposed to tell if a given sequence of numbers is a possible pop sequence of the stack. For example, if M is 5 and N is 7, we can obtain 1, 2, 3, 4, 5, 6, 7 from the stack, but not 3, 2, 1, 7, 5, 6, 4.

Input Specification:

Each input file contains one test case. For each case, the first line contains 3 numbers (all no more than 1000): M (the maximum capacity of the stack), N (the length of push sequence), and K (the number of pop sequences to be checked). Then K lines follow, each contains a pop sequence of N numbers. All the numbers in a line are separated by a space.

Output Specification:

For each pop sequence, print in one line "YES" if it is indeed a possible pop sequence of the stack, or "NO" if not.

Sample Input:

5 7 5
1 2 3 4 5 6 7
3 2 1 7 5 6 4
7 6 5 4 3 2 1
5 6 4 3 7 2 1
1 7 6 5 4 3 2

Sample Output:

YES
NO
NO
YES
NO

大意:M是栈的最大容量,N是栈要输入的元素个数。K为测试用例个数

思路:建栈,如果待输入值比栈顶值大,则比待输入值小且未输入的数字全部依次入栈,若待输入值与栈顶相等,则出栈。若待输入值比栈顶小,说明无法输出。另设变量判定栈中元素是否大于M。

 

 

#include <cstdio>
#include <cstdlib>
#define INIT_STACK_SIZE 100
#define INCREASEMET_SIZE 20

typedef int elementType;
typedef struct{
    elementType *top, *base;
    int sizeS;
    int num;
}sta, *stackPt;

void push(sta &S, elementType x){
    if(S.top-S.base >= S.sizeS){
        S.base = (elementType*)realloc(S.base, S.sizeS+INCREASEMET_SIZE*sizeof(elementType));
        S.top = S.base+S.sizeS;
        S.sizeS += INCREASEMET_SIZE;
    }
    *S.top = x;
    S.top++;
    S.num++;
}

elementType pop(sta &S){
    elementType x;
    x = *(--S.top);
    S.num--;
    return x;
}

elementType top(sta S){
    if(S.top==S.base) return 0;
    return *(S.top-1);
}

void initstack(sta &S){
    S.base = (elementType*)malloc(sizeof(elementType)*INIT_STACK_SIZE);
    if(!S.base) exit(-1);
    S.top = S.base;
    S.num = 0;
    S.sizeS = INIT_STACK_SIZE;
}

void clearStack(sta &S){
    S.top = S.base;
    S.num = 0;
}

int main()
{
    sta S;
    int n, m, k, pt, flag=0;
    int data[1010];

    initstack(S);
    scanf("%d%d%d", &m, &n, &k);

    for(int i=0; i<k; i++){
        for(int j=0; j<n; j++)
            scanf("%d", &data[j]);
        pt=1;
        flag=1;
        for(int j=0; j<=n; j++){
            if(data[j]>top(S)){
                while(data[j]>=pt)
                    push(S, pt++);
                if(S.num>m){
                    flag = 0;
                    break;
                }
                pt=data[j]+1;
                pop(S);
            }else if(data[j]==top(S)){
                pop(S);
            }else if(data[j]<top(S)){
                flag=0;
                break;
            }
        }
        if(flag) printf("YES\n");
        else printf("NO\n");
        clearStack(S);
    }


    return 0;
}

 

posted @ 2021-04-14 15:08  柚子z  阅读(89)  评论(0)    收藏  举报