PAT甲级真题及训练集(6)--1051. Pop Sequence (25)

本文介绍了一个算法问题,如何判断一个序列是否能通过特定顺序的入栈和出栈操作得到。文章详细阐述了问题背景、输入输出规范,并提供了一个C++实现示例。

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

1051. Pop Sequence (25)

时间限制
100 ms
内存限制
65536 kB
代码长度限制
16000 B
判题程序
Standard
作者
CHEN, Yue

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

提交代

/**
作者:一叶扁舟
时间:10:57 2017/6/18
思路:

*/
#include <stdio.h>
#include <string>
#include <stack>
#include <queue>
using namespace std;
#define SIZE 1001

int main(){
	stack<int> s;
	queue<int> q;//用来装原始数字顺序队列
	int test[SIZE];//一次的测试案例入队顺序
	
	int  M;//栈的最大容量
	int N;//数据的长度
	int K;//测试案例的组数
	char result[2][6] = { "NO", "YES" };
	scanf("%d %d %d", &M, &N, &K);
	

	//输入K组测试案例
	for (int i = 0; i < K; i++){
		int flag = 1;//默认1即为Yes,0为No
		//先清空队列,然后初始化队列
		while (!q.empty()){
			q.pop();
		}
		//初始化队列
		for (int i = 1; i <= N; i++){
			q.push(i);
		}
	
		//获取一组的测试数据
		for (int i = 0; i < N; i++){
			scanf("%d",&test[i]);
		}
		//清空栈
		while (!s.empty()){
			s.pop();
		}
		//检验这组数据是否合法
		for (int j = 0; j < N; j++){
			if (s.empty()){
			   s.push(q.front());
			   q.pop();
			}
			if (q.empty() && s.top() != test[j]){
				flag = 0;
				break;
			}
			//如果栈为空时下面的循环不能执行,没办法在执行下面循环之前先将队列的一个数据入栈,压压底
			while (s.size() != M && s.top() < test[j]){
				s.push(q.front());
				q.pop();
			}
			if (s.top() != test[j]){
				flag = 0;
				break;
			}else{
				s.pop();//出栈
			}		
		}

		if (!s.empty()){
			flag = 0;
		}
		//输出
		printf("%s\n",result[flag]);
	
	}
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值