问题描述:html
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.node
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.数组
For each pop sequence, print in one line "YES" if it is indeed a possible pop sequence of the stack, or "NO" if not.app
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
YES NO NO YES NO
分析:dom
对于一个数组,判断他是否符合栈先进后出的顺序:数组元素从左到右,当前元素可以出栈的条件为:一、可以进栈 二、比他小的元素已经按顺序入栈。spa
代码:指针
#include<stdio.h> #include<stdlib.h> #define Max_Size 1000 //栈的存储空间初始分配量 typedef struct node{ int top; //指示栈最上面的元素 int cap; //栈的空间 int Data[Max_Size]; //顺序栈 }Stack; int M, N, K; //M:栈的容量 N:待判断数组元素个数 K:须要被检查的数组个数 //全局变量,做用域为文件做用域 Stack *InitStack() // 构造一个空栈 { Stack *PtrS = (Stack *)malloc(sizeof(struct node));//sizeof(struct node) PtrS -> top = -1; //top初始值为-1表示空栈 PtrS -> cap = Max_Size; return PtrS; } int Top(Stack* PtrS) //获取栈顶元素 { return PtrS -> Data[PtrS -> top]; } void Push(Stack*PtrS, int ele) //将元素ele压入栈中 { if(PtrS -> top == PtrS -> cap-1){ //栈满 printf("FULL\n"); return; } PtrS -> top++; //栈顶指针上移 PtrS -> Data[PtrS -> top] = ele; } void Pop(Stack *PtrS) { if(PtrS -> top==-1){ //栈空 printf("Empty\n"); return; } PtrS -> top--; } int Check_Stack(int v[]) //对于给定的数组,检查数字顺序是否符合栈的规则 { int new_cap = M+1; //栈的容量为M+1 Stack *ps = InitStack(); //新建一个空栈。对于数组中的一个元素,出栈的充分条件为:一、可以进栈 二、它前面的元素已经入栈 int idx = 0; //标记被检查数组元素下标 Push(ps, 0); //初始元素 int num = 1; while(idx != N){ //直到检查到最后一个元素,退出循环 while(idx!=N && (ps->top+1)<new_cap && Top(ps) < v[idx])//一、还有待检查元素 二、栈中元素小于栈的容量 三、栈顶元素小于待检查元素 Push(ps, num++); //将小于待检查元素的数字压入栈中,以后数字加一 if(Top(ps) == v[idx]){ //if(Data[top] == v[idx]) Pop(ps); //printf("Pass"); //该元素经过检查 idx++; } else return 0; } return 1; } int main() { scanf("%d %d %d", &M, &N, &K); int *v =(int *)malloc(sizeof(int)*N);//开辟一个N个int数组的空间,v指向数组首地址 int i; for(;K!=0;--K){ //k-- for(i=0; i != N; ++i) //i<N scanf("%d",v+i); if(Check_Stack(v)) printf("YES\n"); else printf("NO\n"); } return 0; }