1051. Pop Sequence

来源:互联网 发布:windows agent 安装 编辑:程序博客网 时间:2024/06/05 12:03


题目意思是说把一串数字压入栈,然后给你几个序列,请问是否可能是这个数字串出栈的结果?出栈的次序不定。
题目中给的这串数字是1-n连续整数,我想作为人我是怎么判断的呢?要得到某个数字首先得把它前面的东西压进去。如果后一个是更大的数,那么继续压进去,如果是小的进出来并且必须是栈顶上的。
然而我看了别人的算法之后自惭形秽啊。

别人的算法是先把数压进去,一个个地比较栈顶的数字和当前的数字,如果一样就出栈,直到栈空并且在这个过程中没有超过栈的容量就算对



#include <iostream>#include<stack>using namespace std;int n,m,k;int a[1010];int main(){//    freopen("d://jin.txt","r",stdin); cin>>n>>m>>k; for(int r=0;r<k;r++){ for(int j=1;j<=m;j++){ cin>>a[j]; } stack<int> s;int flag=0; int in=1;int i=in;//s.push(in);in++; while(in<=m){                for(;i<=m;i++){ if(a[in]>=i){s.push(i);}else break;  }  if(s.size()>n){flag=1;break;}  else { if(!s.empty()&&s.top()!=a[in]){flag=1;break;}   if(!s.empty()) s.pop();      in++;    }  }  if(flag==1)cout<<"NO"<<endl;  else cout<<"YES"<<endl; }    return 0;}

#include <iostream>#include<cstdio>#include<algorithm>#include<vector>#include<cstring>#include<stack>using namespace std;int n,m,k;int a[1010];int main(){    freopen("d://jin.txt","r",stdin); cin>>n>>m>>k; for(int r=0;r<k;r++){ for(int j=1;j<=m;j++){ cin>>a[j]; }int current=1; stack<int> s;int flag=0;for(int i=1;i<=m;i++){s.push(i);if(s.size()>n){flag=1;break;}while(!s.empty()&&s.top()==a[current]){current++;s.pop();}}  if(s.empty()&&flag==0)cout<<"YES"<<endl;  else cout<<"NO"<<endl; }    return 0;}




0 0