02-线性结构4 Pop Sequence (25分)

来源:互联网 发布:淘宝模板代码怎么使用 编辑:程序博客网 时间:2024/05/16 14:26
02-线性结构4 Pop Sequence   (25分)

Given a stack which can keep MM numbers at most. Push NN numbers in the order of 1, 2, 3, ..., NN 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 MM is 5 and NN 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): MM (the maximum capacity of the stack), NN (the length of push sequence), and KK (the number of pop sequences to be checked). Then KK lines follow, each contains a pop sequence of NN 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 51 2 3 4 5 6 73 2 1 7 5 6 47 6 5 4 3 2 15 6 4 3 7 2 11 7 6 5 4 3 2

Sample Output:

YESNONOYES

NO

这题我用了两种方法,一种是不用栈,一种是用栈模拟。感觉自己还是太渣了,代码写的比较长,但是用栈的那种方法思路还是很清晰的,虽然代码略长,但是思路没有问题。

方法一:把n个数按照顺序一行排列,用一个标记数组判断哪些已经出栈,哪些还未出栈,用两个判断函数判断是否满足条件。

#include<iostream>#include<cstring>#include<cstdlib>using namespace std;#define maxsize 1005int flag[1001];int n,m,k;bool judge(int x,int y){if(x-y==1){return true;}else{if(x>y){for(int i=y+1;i<x;i++){if(!flag[i]){return false;}}return true;}if(x<y){    return true;}}}bool amount(int x){int cnt=0;for(int i=1;i<=x;i++){if(!flag[i])cnt++;}if(cnt>n-1)return false;elsereturn true;}int main(){int a[1001];cin>>n>>m>>k;while(k--){memset(a,0,sizeof(a));memset(flag,0,sizeof(flag));for(int i=0;i<m;i++){cin>>a[i];}if(a[0]>n){cout<<"NO"<<endl;continue;}flag[a[0]]=1;int i;for(i=0;i<m-1;i++){flag[a[i+1]]=1;if(!judge(a[i],a[i+1])||!amount(a[i+1])){cout<<"NO"<<endl;break;}}if(i==m-1){cout<<"YES"<<endl;}}return 0;}
方法二:用栈模拟,栈中元素个数大于限定个数或者栈顶元素不为所要的元素则返回false,否则弹出栈顶元素并返回true。

#include<iostream>#include<stack>#include<cstring>using namespace std;int n,m,k;int mm=0;bool test(stack<int>&s,int x){if(x>mm){for(int i=mm+1;i<=x;i++){s.push(i);}if(s.size()>n||s.top()!=x){return false;}else{s.pop();return true;}}else{if(s.top()!=x){return false;}else{s.pop();return true;}}}int main(){cin>>n>>m>>k;while(k--){mm=0;stack<int>s;int i;for(i=0;i<m;i++){int temp;cin>>temp;if(!test(s,temp)){cout<<"NO"<<endl;while(getchar()!='\n');break;}if(temp>mm)mm=temp;}if(i==m){cout<<"YES"<<endl;}}return 0;}



0 0