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 2
Sample Output:
YES NO NO YES NO 思路:正常模拟,记住每次模拟一个序列的时候需要进行清栈处理。
1 #include <iostream> 2 #include <cstdio> 3 #include <stack> 4 using namespace std; 5 #define MAX 1010 6 int data[MAX]; 7 int main(int argc, char *argv[]) 8 { 9 int M,N,K; 10 stack<int> st; 11 scanf("%d%d%d",&M,&N,&K); 12 for(int i=0;i<K;i++) 13 { 14 for(int j=0;j<N;j++) 15 scanf("%d",&data[j]); 16 bool flag=false; 17 int index=0; 18 int pt=1; 19 st.push(pt++); 20 while(st.size()<=M) 21 { 22 while(st.top()<data[index]&&st.size()<=M) 23 { 24 st.push(pt++); 25 } 26 if(st.size()>M) 27 break; 28 if(st.top()>data[index]) 29 { 30 flag=false; 31 break; 32 } 33 else if(st.top()==data[index]) 34 { 35 st.pop(); 36 index++; 37 if(index==N) 38 { 39 flag=true; 40 break; 41 } 42 if(st.empty()) 43 { 44 if(pt<=N) 45 { 46 st.push(pt++); 47 } 48 else 49 { 50 break; 51 } 52 } 53 } 54 } 55 if(flag) 56 printf("YES\n"); 57 else 58 printf("NO\n"); 59 while(!st.empty()) 60 { 61 st.pop(); 62 } 63 64 } 65 return 0; 66 }