PAT甲级 1051. Pop Sequence (25)

来源:互联网 发布:apache本地服务器搭建 编辑:程序博客网 时间:2024/06/15 14:38

题目:

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 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
思路:

这道题我是看:http://blog.csdn.net/u014646950/article/details/47430401这位作者的思路做的。一开始只想到了用数组和游标,没想到直接模拟出栈入栈的情况。

代码:

#include<iostream>#include<stack>#include<algorithm>using namespace std;int main(){int M, N, K;cin >> M >> N >> K;int q[1001] = { 0 };int j,i = 0;for (; i < K; ++i){for (j = 1; j <= N; ++j){cin >> q[j];        //队列的第j位是q[j],输入顺序}//模拟入栈、出栈的过程stack<int> s;bool flag = 1;int index = 1;int dig = 1;while (flag && index <= N){while (s.empty() || (q[index] != s.top()&& s.size()<M)){//把数字按顺序加到现在的数值,注意栈最大容量s.push(dig);dig++;}if (q[index] != s.top()) {flag = 0;}else{s.pop();//踢出该数index++;}}if (index > N && flag){cout << "YES" << endl;}elsecout << "NO" << endl;}system("pause");return 0;}