PAT A1051 2019.07.13 【栈模拟】

该博客介绍了PAT编程竞赛中的一道题目A1051,涉及栈的数据结构。问题核心在于给定栈的最大容量M、按顺序推入的数字N以及多个可能的出栈序列K,判断这些序列是否符合栈的特性。博主提供了一个解决方案,即模拟每个出栈序列的过程,如果在模拟过程中发现不符合栈的后进先出原则,则该序列非法。对于每个测试用例,输出'YES'表示序列合法,'NO'表示不合法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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"); 

				
	}// 每组样例 
	
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值