1051 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
思路:
定义一个栈,进行出栈模拟。
1、循环下标从1开始,因为进栈序列是从1,开始的。
2、如果当前栈中元素个数大于最大值m则返回false
3、如果栈顶元素和出栈序列第一个元素相同,则循环出栈,直到栈顶元素和出栈序列元素不匹配
4、循环结束后,如果栈中还有元素则返回false
5、否则,返回true
详细请看代码
#include<iostream> #include<vector> #include<algorithm> #include<queue> #include<string> #include<map> #include<set> #include<stack> using namespace std; bool check(int a[],int n,int m) { stack<int> st; int top=1; for(int i=1; i<n+1; i++) { st.push(i); if(st.size()>m) return false; //如果栈顶元素等于出栈序列第一个则出栈 while(!st.empty()&&st.top()==a[top]) { st.pop(); top++; } } if(!st.empty()) return false; return true; } int main() { int m,n,k; cin>>m>>n>>k; int a[n+1]; for(int i=0; i<k; i++) { for(int j=1; j<n+1; j++) cin>>a[j]; if(check(a,n,m)) cout<<"YES"<<endl; else cout<<"NO"<<endl; } return 0; }
posted on 2019-01-23 13:55 ZhangのBlog 阅读(106) 评论(0) 编辑 收藏 举报