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)两者相同,两个索引都累加
2)stack 顶部元素等于待匹配的数组,则出栈,待匹配索引累加
3)不同则入栈,原数组索引累加
Debug:
1)for(int 待匹配数组/原数组索引) 因为在for循环的条件中,必然会使用++的递增,这就会与循环语句内的条件冲突,所以使用while循环,循环条件使用原数组索引<length进行判断;
2)在while循环结束时,如果empty就返回false。这个想法是错误的,因为在非empty时,stack内部可能正好有待匹配数组的逆序排列,因此在循环外部,也要在顶部元素和待匹配数组元素相同时,依次排出
3)在排出之后,如果仍有剩余元素,证明那是真的不匹配。
也就是如果 7 6 5 4 3 2 1 是待匹配元素的话(此时stack深度为7)
4)在每次judge后,如果stack是全局的,需要释放掉,但是因为stack没有clear函数,需要一次pop,所以最好还是使用judge内部局部声明一个stack的做法。(这种历史影响因素已经错过好几次,注意!)
#include <iostream>
#include <stack>
#include <vector>
using namespace std;
/* run this program using the console pauser or add your own getch, system("pause") or input loop */
vector<int> vec;
vector< vector<int> > vec_array;
int depth,vec_length,seq_num;
bool judge(vector<int> &vec_tmp){
stack<int> stack_int;
int j=0,k= 0 ;
//for(int i =0;i<vec_length;i++){
while(j<vec_length){
// j is the id in vec
// k is the id in vec_tmp
if (vec_tmp[k]==vec[j]){
j++;
k++;
}else if ((!stack_int.empty())&&(stack_int.top()==vec_tmp[k])){
stack_int.pop();
k++;
}
//else if((!stack_int.empty())&&(stack_int.top()!=vec_tmp[i])){
else{
stack_int.push(vec[j]);
j++;
}
if(stack_int.size()>=depth) return false;
}
while(!stack_int.empty()){
if(stack_int.top()==vec_tmp[k]){
stack_int.pop();
k++;
}else break;
}
if (stack_int.empty())return true;
else return false;
}
int main(int argc, char** argv) {
cin>>depth>>vec_length>>seq_num;
for(int i=0;i<vec_length;i++){
vec.push_back(i+1);
}
for(int i=0;i<seq_num;i++){
vector<int> vec_tmp;
for(int j=0;j<vec_length;j++){
int data;
cin>>data;
vec_tmp.push_back(data);
}
vec_array.push_back(vec_tmp);
}
for(int i=0;i<seq_num;i++){
vector<int> vec_tmp;
vec_tmp = vec_array[i];
if(i==3){
int debug = 0;
}
if(judge(vec_tmp)) printf("YES\n");
else printf("NO\n");
}
return 0;
}