1051. Pop Sequence (25)
题目连接:https://www.patest.cn/contests/pat-a-practise/1051原题如下:
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
我觉得这道题对我来说已经很难了,难在逻辑关系上。我刚开始没想到用一个数去记录push进堆栈的元素的数字,并在刚开始判断数是否大于
当前可以push进的元素的最大值。每当pop的时候,可以Push进的元素的最大值++。
参考了别人的代码:
1 #include<stdio.h> 2 #include<stack> 3 #define MAXN 1005 4 using namespace std; 5 6 int main() 7 { 8 int M,N,K; 9 scanf("%d %d %d",&M,&N,&K); 10 int sequence[MAXN]; 11 while (K--) 12 { 13 for (int i=0;i<N;i++)scanf("%d",&sequence[i]); 14 int MaxNum,flag,index; 15 MaxNum=M; 16 flag=1; 17 index=1; 18 stack<int>s; 19 20 for (int i=0;i<N;i++) 21 { 22 if (sequence[i]>MaxNum) 23 { 24 flag=0;//printf("%d afds\n",sequence[i]); 25 break; 26 } 27 else 28 { 29 while (s.empty() || (!s.empty()&&s.top()!=sequence[i]&&index<=sequence[i])) 30 { 31 // printf("%d %d\n",index,sequence[i]); 32 s.push(index++); 33 } 34 if (s.top()!=sequence[i]) 35 { 36 flag=0;//printf("%d\n",sequence[i]); 37 break; 38 } 39 } 40 s.pop(); 41 MaxNum++; 42 } 43 44 if (flag)printf("YES\n"); 45 else printf("NO\n"); 46 } 47 return 0; 48 }