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
1、理解题意
给出一个容量限制为m的栈,分别把1、2、3……n依次进栈,并给出一系列的出栈顺序,判断该顺序是否可能。
2、解题思路
将1~n依次入栈,在入栈的过程中,如果入栈的元素恰好等于出栈序列当前等待出栈的元素,就让栈顶元素出栈。同时把出栈序列当前等待出栈元素位置标记后移一位,此时只要栈顶元素依然等于该出栈序列当前等待出栈的元素,就继续出栈。对当前序列处理的步骤如下:
(1)判断此时的栈是否为空,如果不是,则清空栈;
(2)使用一个整型数组temp存放当前序列,下标从1开始,设置整型变量t来标记序列中带出栈的元素在数组中的位置;
(3)设置bool型变量flag表示序列是否合法,初始值为true;
(4)1~n依次入栈,若超出栈的最大容量m,flag为false,退出循环;入栈元素从1开始枚举i,若栈不为空且i等于当前t所指的待出栈元素,则i出栈,t指向序列下一个位置,循环进行;
(5)循环结束后,若栈空且flag==true,则序列合法,否则不合法。
#include<cstdio>
#include<stack>
#include<string>
#include<iostream>
using namespace std;
const int maxn=1010;
stack<int> st;
int temp[maxn];
int n,m,k;
string str[maxn];
int main(){
scanf("%d %d %d",&m,&n,&k);
for(int i=0;i<k;i++){//循环k次
while(!st.empty()){
st.pop();
}
for(int j=1;j<=n;j++){//数组下标1~n
scanf("%d",&temp[j]);
}
int t=1;
bool flag=true;//该语句一定放置在for循环里
for(int j=1;j<=n;j++){//从1~n个数入栈
st.push(j);
if(st.size()>m) {//超出栈的最大范围
flag=false;
break;
}
while(!st.empty()&&st.top()==temp[t]){//栈不空且栈顶元素等于出站序列当前所指元素是
st.pop();//栈顶元素出栈,
t++;//指向下一个出栈元素
}
}
if(st.empty()==true&&flag==true){
//printf("YES\n");
str[i]="YES";
} else{
//printf("NO\n");
str[i]="NO";
}
}
for(int i=0;i<k;i++){
cout<<str[i]<<endl;
}
return 0;
}
3、知识总结
(1)关于栈的应用:
//使用栈时要添加的头文件
#include<stack>
using namespace std;
//定义一个元素为整型的栈
stack<int> st;
//压栈
int k;
st.push(k);
//出栈
st.pop();
//访问栈,只能从栈顶开始
st.top();
//清空栈
while(!st.empty()){
st.pop();
}