题目
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
代码
一开始会认为比较棘手,后来在纸上多寻找规律,不断摸索规律,也陆陆续续画出了思维导图一样的逻辑。
#include<iostream>
#define MaxSize 1001
using namespace std;
int check(int o[],int n,int m){
int a[m+1]={0};//最多容纳m个数的栈,最后一个位置是用来判断是否溢出
int tag[n+1]={0};//用来标记数字是否进去过
//如果tag[1]=1,说明数字1进去过,数组下标从1开始
int top=-1;//标记栈顶元素的位置
for(int i=0;i<n;i++){
if(tag[o[i]]==1&&o[i]!=a[top]) {//若已经访问过了,但是栈顶元素不同
//cout<<"No1 a[top]="<<a[top]<<" i="<<i<<endl;
cout<<"NO"<<endl; return 0;
}
if(top!=-1&&o[i]==a[top]){//跟栈顶元素相同
top--;//将该元素出栈
//cout<<"出栈"<<endl;
}
else{
for(int b=1;b<=o[i];b++){
if(tag[b]==0) {
a[++top]=b;tag[b]=1;
//cout<<"a[top]"<<a[top]<<" = "<<b<<endl;
if(top==m) {
cout<<"NO"<<endl; return 0;}
}
}
top--;
}
}
cout<<"YES"<<endl;return 0;
}
int main(){
int M,N,n;
int origin[MaxSize];
cin>>M>>N>>n;
for(int q=0;q<n;q++){
for(int p=0;p<N;p++)
cin>> origin[p];
check(origin,N,M);
}
return 0;
}
注意:
- 如果不把数组都初始化,很可能会错。小心驶得万年船,初始化总没错。
- 写的时候把tag[o[i]]写成了tag[i],写if的时候,又写成了if (a = b)这种,反思反思。
- 这几天写题目写得多,感觉越来越顺手了,思路很快就出来了(然而debug了好久= =)。