线性结构3 Pop Sequence(PAT)
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
题意
第一行输入 M, N,T
M代表栈的容量,N为序列长度,T为测试组数
我们可以向容量为M的栈中按照1 , 2, 3..的顺序推入 1 ,2, 3.. , 可以任意弹出。问能否输出给定序列。
样例 5 6 4 3 7 2 1
推入 1 2 3 4 5 , 弹出 5, 此时 1 2 3 4
输入 6 ,推入 6, 此时 1 2 3 4 6 , 弹出6 ,此时 1 2 3 4
输入 4 ,弹出 4,此时 1 2 3
输入 3 ,弹出 3,此时 1 2
输入 7,推入 7 , 此时 1 2 7,弹出 7,此时 1 2
输入 2, 弹出 2 , 此时 1
输入1 ,弹出 1. 输出 YES!
直接模拟题意解决
#include<iostream> #include<cstdio> #include<stack> using namespace std; int main(){ int n,m,t; scanf("%d%d%d",&n,&m,&t); stack<int>st; for(int i = 0;i<t;i++){ int tmp = 1; bool False = 0; for(int j=0;j<m;j++){ int input ; scanf("%d",&input); while(st.size() <= n && !False){ //满足条件就不断推入 1,2,3... if(st.empty() || st.top() != input) st.push(tmp++); else if(st.top() == input){ //如果栈顶元素与输入的一样了,就弹出。 st.pop(); break; } if(st.size() > n) { False = 1; break; //超过栈的范围了 } } } if(!False) printf("YES\n"); else printf("NO\n"); while(!st.empty()) st.pop(); } return 0; }