本文主要是介绍PAT甲级真题及训练集(6)--1051. Pop Sequence (25),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
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 2Sample 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 1001int 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;
}
这篇关于PAT甲级真题及训练集(6)--1051. Pop Sequence (25)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!