题目
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 Nis 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
运行结果
Case | Hint | Result | Run Time | Memory |
---|---|---|---|---|
0 | sample乱序,一般的Y&N | Accepted | 3 ms | 416 KB |
1 | 达到最大size后又溢出 | Accepted | 2 ms | 384 KB |
2 | M==N | Accepted | 2 ms | 416 KB |
3 | 最大数 | Accepted | 3 ms | 384 KB |
4 | 最小数 | Accepted | 2 ms | 384 KB |
5 | 卡特殊错误算法(通过比较大小判断) | Accepted | 3 ms | 384 KB |
程序
#include<iostream>
using namespace std;
string CheckPop(int check_pop[], int N, int M);
int main()
{
/*
//测试用例
string CurrResult;
static int M = 5;
static int N = 7;
static int K = 5;
int check_pop1[N] = {1,2,3,4,5,6,7};
int check_pop2[N] = {3,2,1,7,5,6,4};
int check_pop3[N] = {7,6,5,4,3,2,1};
int check_pop4[N] = {5,6,4,3,7,2,1};
int check_pop5[N] = {1,7,6,5,4,3,2};
int check_pop6[N] = {6,5,4,3,2,1,7};
CurrResult = CheckPop(check_pop6, N, M);
cout << CurrResult;
*/
int M;//the maximum capacity of the stack
int N;//the length of push sequence
int K;//the number of pop sequences to be checked
string CurrResult;
cin >> M;
cin >> N;
cin >> K;
//根据题目要求输入
int check_pop[N];
string AllResult[K];
for(int i=0; i<K; i++){
for(int j=0; j<N; j++){
cin >> check_pop[j];
}
CurrResult = CheckPop(check_pop, N, M);
AllResult[i] = CurrResult;
}
//print
for(int i=0; i<K; i++){
cout << AllResult[i] << endl;
}
return 0;
}
string CheckPop(int check_pop[], int N, int M)
{
string result;
int stack_[10000];//设置堆栈,可用堆栈最大为M
int push_seq_i = 1;//入栈序列元素下标,下标即为元素值
int check_pop_i = 0;//出栈序列元素下标
int stack_i = -1;//堆栈为空,栈顶下标
int CurrPopData;//当前出栈元素值
//遍历所有待判断的出栈序列元素
while(check_pop_i < N){
//出栈元素大于目前堆栈中的最大元素,则继续将元素入栈
while(push_seq_i <= check_pop[check_pop_i]){
//当堆栈未满时,允许入栈操作
if(stack_i < M-1){
++stack_i;
stack_[stack_i] = push_seq_i;
}
//堆栈满,还要求入栈操作,表示出栈序列不符合
else{
result = "NO";
return result;
}
++push_seq_i;
}
//出栈操作,取出栈顶元素
CurrPopData = stack_[stack_i];
--stack_i;
//当前出栈元素等于待判断的出栈元素
if(check_pop[check_pop_i] == CurrPopData)
++check_pop_i;
//当前出栈元素不等于待判断的出栈元素,则输出不符合
else{
result = "NO";
break;
}
}
//遍历完所有待判断出栈元素,则输出符合
if(check_pop_i == N){
result = "YES";
}
return result;
}