[PAT A1051]Pop Sequence
题目描述
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.
输入格式
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.
输出格式
For each pop sequence, print in one line “YES” if it is indeed a possible pop sequence of the stack, or “NO” if not.
输入样例
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
输出样例
YES
NO
NO
YES
NO
**思路:**以3 2 1 7 5 6 4为例,第一个出栈的是3,要出栈必须得先入栈,入栈的顺序是1,2,3,…所以3想出栈必须先压1,2,3入栈,然后才能出3;第二个出栈的是2,查看堆栈里面栈顶确实是2,那就直接出2,同理1也是一样,第四个出栈的是7,这是1,2,3都已经入过了,那么从4开始入,入4,5,6,7,然后把7出了,第五个出栈的是5,一看堆栈栈顶是6,那不行啊,想出5必须先出6,那么自然这个出栈顺序就是不行的。
#include<iostream>
#include<string>
#include<stack>
using namespace std;
int main()
{
int n, m, k;
stack<int> st;
scanf("%d%d%d", &n, &m, &k);
for (int i = 0; i < k; i++) {
int p = 1; //当前需要压入的元素值
bool judge = true; //判断是否该序列符合条件
while (!st.empty()) st.pop(); //首先清空栈
for (int j = 0; j < m; j++) {
int temp;
scanf("%d", &temp); //当前需要出栈的元素
while (p <= temp) { //从p到当前需要出栈的元素逐一压栈
st.push(p);
if (st.size() > n) { //一旦溢出,就判错
judge = false;
break;
}
p++;
}
if (st.top() != temp) { //如果栈顶元素不为temp,也判错
judge = false;
continue;
}
else st.pop(); //栈顶元素就是需要出栈的元素,那么pop掉该元素
}
if (judge) printf("YES\n");
else printf("NO\n");
}
return 0;
}