02-线性结构4 Pop Sequence(25 分)
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
#include<stdio.h>
#define MAXSIZE 1000
typedef struct SNode *Stack;
struct SNode{
int Date[MAXSIZE];
int Top;
}snode;
int Push(Stack PtrS,int item){
if(PtrS->Top==MAXSIZE-1)
return 0;
PtrS->Date[++(PtrS->Top)] = item;
return 1;
}
int Pop(Stack PtrS){
if(PtrS->Top==-1)
return 0;
return PtrS->Date[(PtrS->Top)--];
}
int main(){
int m,n,k,i,j;
Stack p;
scanf("%d %d %d",&m,&n,&k);
int v[n+1];
for(i=0;i<k;i++){
int current = 1;
p=&snode;
p->Top = -1;
for(j=1;j<n+1;j++){
scanf("%d",&v[j]);//建立一个数组,下标从1开始,将需要判断的出栈顺序放进去
}
for(j=1;j<=n;j++){
Push(p,j);
if(p->Top+1>m)//如果超过栈的容量,证明栈已满,验证的出栈顺序不存在
break;
while(p->Top!=-1 && p->Date[p->Top]==v[current]){//判断栈顶元素和需要验证的出栈顺序之间的关系
Pop(p);
current++;
}
}
if(current==n+1)
printf("YES\n");
else printf("NO\n");
}
return 0;
}
这道题就是说给你一个容量为M的栈,有1到N共N个数,将他们入栈,然后判断出栈顺序是否存在,我这里建立了一个栈和一个数组(下标从1开始),数组里面保存的是我需要判断的出栈顺序,当栈顶的元素和我数组下标指示的数一样时,Pop这个数,并且数组下标加1,然后要么判断栈顶位置为-1或者下标到达长度加一处,则输出YES