题目
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的栈,把1、2、3…N依次压入栈中,过程中可以随意出栈,判断能否得到给定的k个出栈序列,能则打印YES,否则打印NO。
解答
将1-N按序压入栈中,若某次压栈后栈顶元素和序列中指针处的元素相同,则出栈并将指针后移一位,若过程中栈中元素不溢出且结束后栈为空则代表可以得到该出栈序列。
代码如下:
#include <cstdio>
#include <stack>
#include <vector>
using namespace std;
int main(){
stack<int> st;
int j,m,n,k,temp,i;
bool flag = true;
scanf("%d %d %d",&m,&n,&k);
vector<int> pops;
while(k--){
flag = true;
i = 0;
while(!st.empty()){
st.pop();
}
pops.clear();
for(j=1;j<=n;j++){
scanf("%d",&temp);
pops.push_back(temp);
}
for(j=1;j<=n;j++){
st.push(j);
if(st.size() > m){
printf("NO\n");
flag = false;
break;
}
while(!st.empty() && st.top() == pops[i]){
st.pop();
i++;
}
}
if(flag && !st.empty()){
printf("NO\n");
flag = false;
}
if(flag) printf("YES\n");
}
return 0;
}