02-线性结构4 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 2
Sample Output:
YES NO NO YES NO
思路:准备2个栈,一个保存入栈序列,一个保存出栈序列。将1-n入栈,在入栈过程中如果入栈序列和出栈序列一致,就出使栈顶元素出栈,出栈后还是相等就继续出栈(此处一个循环,直到栈顶元素不等位置),然后继续入栈
#include<iostream> #include<stack> using namespace std; int main() { int m,n,k;//栈容量,序列长度,要检查的序列数 scanf("%d %d %d",&m,&n,&k); while(k--)//k个要检查的序列 { bool flag = 1;//一开始假设这个序列没错 stack<int> st;//入栈序列 while(!st.empty())//入栈之前栈必须要空 st.pop(); int arr[n+1];//保存出栈的序列 int cur =1;//栈顶指针 for(int i=1;i<=n;i++)//输入出栈序列 { scanf("%d",&arr[i]); } for(int i=1;i<=n;i++)//入栈序列开始进栈 { st.push(i); if(st.size()>m)//超过了栈的容量就停止 { flag = false; } while(!st.empty()&& st.top()==arr[cur])//栈顶元素相同就出栈 { st.pop(); cur++; } } if(st.empty()&&flag == true) cout<<"YES\n"; else cout<<"NO\n"; } return 0; }