Given a stack which can keep M numbers at the most. Push n numbers in the order of 1, 2, 3, ..., N and pop randomly. You were 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 are 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 the one test case. For each case, the first line contains 3 numbers (all no more than): M (the maximum capacity of the stack), N (The Le Ngth 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 is separated by a space.
Output Specification:
For each pop sequence, print on one line "YES" if it is indeed a possible pops sequence of the stack, or "NO" if not.
Sample Input:
5 7 51 2 3 4 5 6 73 2 1 7 5 6 47 6 5 4 3 2 15 6 4 3 7 2 11 7 6 5 4 3 2
Sample Output:
Yesnonoyesno
#include <iostream>#include<stack>using namespacestd;intMain () {intM//Maximum capacity of the stack intN//The length of push sequence intK//The number of pop sequence to be checkedCIN >> M >> N >>K; intI, J; intinput, temp; BOOLFlag =true; Stack<int>STA; for(i =0; i < K; i++) {Temp=1; Flag=true; for(j =0; J < N; J + +) {cin>>input; while(Sta.size () <= M &&flag) { if(Sta.empty () | | sta.top ()! =input) {Sta.push (temp++); } Else if(Sta.top () = =input) {Sta.pop (); Break; } } if(Sta.size () >M) {flag=false; } } if(flag) cout<<"YES"<<Endl; Elsecout<<"NO"<<Endl; while(!sta.empty ()) Sta.pop (); } return 0;}
Data structure Exercise 02-linear structure 3. Pop Sequence (25)