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.
<h6>(给定一个最多只能保留 M 数的堆栈。按 1、2、3、...、N、随机弹出的顺序推 N 个数字。您应该判断给定的数字序列是否可能是堆栈的弹出序列。例如,如果 M 为 5,N 为 7,我们可以从堆栈中获取 1、2、3、4、5、6、7,但不能从堆栈中获取 3、2、1、7、5、6、4。)</h6>
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.
(输入规格:
每个输入文件包含一个测试用例。对于每种情况下,第一行包含 3 个数字(全部不超过 1000):M(堆栈的最大容量)、N(推送序列的长度)和 K(要检查的弹出序列数)。然后 K 行跟随,每个行包含 N 个数字的弹出序列。行中的所有数字都由空格分隔。)
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.
(输出规格:
对于每个弹出序列,如果确实可能是堆栈的弹出序列,则打印一行"YES";如果不是,则打印"否"。)
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-n依次入栈,在入栈过程中如果入栈的元素恰好等于出栈序列当前等待出栈的元素,那么就让栈顶元素出栈,同时把出栈序列当前等待出栈的元素位置后移1位。如果栈顶元素仍然等于出栈序列当前元素,则继续出栈。
#include <stdio.h>
#include <stack>
using namespace std;
const int maxn=1010;
int arr[maxn];
stack<int>st;
int main(){
int M,N,n;
scanf("%d%d%d",&M,&N,&n);
for(int i=0;i<n;i++){
//清空栈
while(!st.empty()){
st.pop();
}
//将待验证的序列储存在数组arr[]中
for(int j=0;j<N;j++){
scanf("%d",&arr[j]);
}
//k为待验证序列序号,l为要压如栈的数字序列:1,2,3,4,5,6,7,count为压入到栈中的个数
int k=0,l=1,count=0;
st.push(l); //压入第一个
count++; //记录栈中元素个数
//k小于序列个数,count小于等于栈的容量
while(k<N && 0<=count&&count<=M){
//栈不为空且栈顶元素为待验证序列元素
if(!st.empty()&&st.top()==arr[k]){
k++; //待验证序列递增
st.pop(); //弹出栈顶元素
count--; //栈中个数减一
}
else{
l++; //压入下一个元素
st.push(l);
count++; //栈中元素个数加一
}
}
//k=N代表已经将待验证序列全部验证完毕,没有错误
if(k==N){
printf("YES\n");
}
else{
printf("NO\n");
}
}
return 0;
}