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.
给出一个最多可以存贮M个数字的栈。按照1,2,3,....,N的顺序进栈且随机出栈。你要判断一个给出的数字序列是否可能是栈的出栈序列。例如,M=5且N=7时,我们可以从栈中获得1, 2, 3, 4, 5, 6, 7,而不是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.
每一个输入文本包含了一个测试用例。每个用例中,第一行包含了3个均小于1000的数字:栈的最大容量M,进栈的数字序列长度N,被检查的出栈序列数K。接下来的K行,每一行都是N个数字的出栈序列。每个数字间用空格间隔开。
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.
对每一个出栈序列,若确实是可能的出栈序列,输出“YES”,否则输出“NO”。
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>
#include <stdlib.h>
#define maxsize 1000
typedef struct SNode{
int capacity;
int top;
int data[maxsize];
}*Stack;
Stack CreatStack(int M)//初始化一个空栈
{
Stack s=(Stack)malloc(sizeof(struct SNode));
s->top=-1;
s->capacity=M;
return s;
}
int Push(Stack s,int x)//入栈,成功返回1,若溢出返回0
{
if(s->capacity==s->top+1)
{
return 0;
}else{
s->data[++s->top]=x;
return 1;
}
}
void Pop(Stack s)//出栈
{
s->top--;
}
int Top(Stack s)//返回栈顶元素
{
if(s->top>=0)
{
return s->data[s->top];
}else{
return -1;
}
}
int IsPopPossible(int pop[],int M,int N)//题目所考察的最重要的函数,判断是否可能为出栈序列
{
Stack s=CreatStack(M);
int head=0;//用例的下标
for(int i=1;i<=N;i++)
{
if(!Push(s,i))//入栈,并且判断是否溢出
{
return 0;
}
while(Top(s)==pop[head])//栈顶元素和下标指向的元素是否相等
{
Pop(s);
head++;//下标后移
}
}
if(head==N)//出栈元素数和用例元素数相等
{
return 1;
}else{
return 0;
}
}
int main()
{
int M,N,K;//栈的最大容量M,进栈的数字序列长度N,被检查的出栈序列数K
scanf("%d %d %d",&M,&N,&K);
int pop[N]; //出栈的测试用例
for(int i=0;i<K;i++)
{
for(int j=0;j<N;j++)//循环读取每一条出栈序列的元素并判断
{
scanf("%d",&pop[j]);
}
if(IsPopPossible(pop,M,N))
{
printf("YES\n");
}else{
printf("NO\n");
}
}
return 0;
}