POJ1363--出栈顺序(栈的应用)

来源:互联网 发布:加里纳利数据 编辑:程序博客网 时间:2024/06/03 00:29

题目:http://poj.org/problem?id=1363

自己写完之后看到网上的做法的确感觉自己的算法很慢也很耗时,但是还是贴一下。题意不多说(当然也是读了很久才看懂),入栈顺序一定1,2,3...N,给你出栈序列,如果能按着出栈序列出栈则输出"Yes",否则输出"No"。


算法:

1.设置三个stack:A,B,buffer。A:N-->1依次入栈,栈顶为1;B:出栈顺序从尾到头入栈;buffer:缓冲区;
2.首先考察B的栈顶元素知道B为空:
2.1如果buffer栈为空或者B的栈顶元素大于buffer的栈顶元素,那么从A中将小于等于B栈顶元素的所有元素入栈buffer,然后将buffer的栈顶元素和B的栈顶元素都弹出(因为相等),然后继续回到2。
2.2.如果buffer的栈顶元素和B的栈顶元素相等,那么将buffer和B的栈顶元素弹出,回到2。
2.3.如果buffer的栈顶元素大于B的栈顶元素,那么将break(说明不能出栈)。
3.如果B为空,那么输出yes;否则如果B不为空,输出no。


代码:

#include<iostream>#include<stack>#include<string>#include<cstring>using namespace std;const int MAX = 1001;int main(){int n;int array[MAX];while(cin>>n){if(n==0){    break;}//cout<<"n = "<<n<<endl;while(cin>>array[0]){stack<int> A,B,buffer;if(array[0]==0){break;}for(int i=1;i<n;i++){cin>>array[i];}for(int i=n-1;i>=0;i--){//cout<<array[i]<<" ";B.push(array[i]);A.push(i+1);}while( !B.empty() ){if( buffer.empty() || B.top() > buffer.top() ){while( !B.empty() && !A.empty() && B.top() >= A.top() ){                        //cout<<"B.top() = "<<B.top()<<" A.top() = "<<A.top()<<endl;int tmp = A.top();//cout<<"tmp = "<<tmp<<endl;buffer.push(tmp);A.pop();}B.pop();buffer.pop();continue;}else if( !buffer.empty() && !B.empty() && buffer.top()==B.top() ){B.pop();buffer.pop();continue;}else if( !buffer.empty() && !B.empty() && B.top() < buffer.top() ){break;}}//whileif( B.empty() ){cout<<"Yes"<<endl;}else{cout<<"No"<<endl;}}//whilecout<<endl;}//while    //system("pause") ;return 0;}



Run IDUserProblemResultMemoryTimeLanguageCode LengthSubmit Time12373669niuliguo1363Accepted732K610MSG++1363B2013-12-12 16:33:01

注明出处:http://blog.csdn.net/lavorange/article/details/17284799

0 0