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
解题思路:
题目要求判断给出的数组是否符合出栈能形成的顺序。
所以我们肯定需要定义一个栈:
当给出数组当前的数字与栈顶的数字不相同且栈的大小符合题目要求时,就继续入栈;相同时出栈,空栈时出栈。最后判断数组里的所有数字是否都能被栈输出即可,判断代码如下:
bool is_right(vector<int> a){
stack<int> order;//栈每次使用过后要清空,所以干脆定义在这里
int in_number[N];
for(int i=0;i<N;i++){//1-N的数字
in_number[i]=i+1;
}
int index = 0;
order.push(in_number[index++]);//先将第一个数字入栈
int i=0;
for(;i<a.size();){
if(a[i]!=order.top()&&order.size()<M){//当不相同且栈容量够时入栈
order.push(in_number[index]);
index++;
}
else if(a[i] == order.top()){//相同时出栈,并继续向后判断
i++;
order.pop();
}
else{
break;
}
if(order.empty()) order.push(in_number[index++]);//栈为空时入栈
}
if(i<a.size()) return false;
return true;
}
易错点:
1. 空栈的时候记得入栈,可以避免一进一出的情况下出错;
2. 每次使用完栈记得清空!!!!!
代码:
#include<bits/stdc++.h>
using namespace std;
int M;//栈的最大容量
int N;//数组长度
int K;//需要检查的数组数量
bool is_right(vector<int> a){
stack<int> order;//栈每次使用过后要清空,所以干脆定义在这里
int in_number[N];
for(int i=0;i<N;i++){//1-N的数字
in_number[i]=i+1;
}
int index = 0;
order.push(in_number[index++]);//先将第一个数字入栈
int i=0;
for(;i<a.size();){
if(a[i]!=order.top()&&order.size()<M){//当不相同且栈容量够时入栈
order.push(in_number[index]);
index++;
}
else if(a[i] == order.top()){//相同时出栈,并继续向后判断
i++;
order.pop();
}
else{
break;
}
if(order.empty()) order.push(in_number[index++]);//栈为空时入栈
}
if(i<a.size()) return false;
return true;
}
int main(){
cin>>M>>N>>K;
vector<int> number[K];
for(int i=0;i<K;i++){
for(int j=0;j<N;j++){
int t;
cin>>t;
number[i].push_back(t);
}
if(is_right(number[i])) cout<<"YES"<<endl;
else cout<<"NO"<<endl;
}
return 0;
}