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 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;
}