1051 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
思路分析
已知入栈序列,判断给定的出栈序列是否合法
注意栈有大小限制
我的实现方法:每组样例都进行模拟出栈操作,如果一组数据中,只要有1个数据不合法,那么这组数据为不合法,给一个标记,在这组样例输入完成后,打印 YES 或者 NO
#include<cstdio>
#include<iostream>
#define MAX 1010
int main()
{
int stackCap;//栈容量
int stack[MAX]={0};//栈定义
int top=0;
int n=0; //入栈序列长度
int time=0;//测试数据次数
scanf("%d %d %d",&stackCap,&n,&time);//输入第一行
int temp=1;//要入栈的数字--首先是1
int popNum=0;//要出栈的数字
int falseFlag;//失败标志,如果为 1 则输出NO
while(time--)
{
falseFlag = 0;
top=0;//初始化栈
temp=1;
for(int i=1;i<=n;i++)
{
scanf("%d",&popNum);//输入每个需要出栈的数字
while(1)
{ //无限循环
if(top<stackCap) //如果栈不满
{
if(top==0)//栈空先入栈
{
stack[++top]=temp; //栈不满则先入栈 //temp初始为1
temp++; //入栈后temp为2 为下次要入栈的元素
}
//此后栈非空
if(stack[top]==popNum)//如果栈顶匹配
{
stack[top]=0;
top--;
break;//出栈后继续输入下一个数字--结束掉while循环
}
else //如果栈顶不匹配
{
stack[++top]=temp; //栈不满则先入栈 //temp初始为1
temp++; //入栈后temp为2 为下次要入栈的元素
continue;
}
}
else//如果栈满
{
if(stack[top]==popNum)//如果栈满而且栈顶是要出栈元素
{
stack[top]=0;
top--;
break;//出栈后继续输入下一个数字--结束掉while循环
}
else//栈满且栈顶不是要出栈元素
{
//printf("NO\n");//则不可能得到这个出栈序列
falseFlag = 1;
break;
}
}
} //while(1)
}//每个要出栈的数字
if( falseFlag == 1)printf("NO\n");
else printf("YES\n");
}// 每组样例
}