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

本文提供了一种解决POJ 1363问题的方法,该问题涉及判断给定的出栈序列是否能通过特定的入栈顺序实现。采用三个栈A、B、buffer进行操作,通过一系列条件判断来验证序列的有效性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目: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;
				}
			}//while

			if( B.empty() )
			{
				cout<<"Yes"<<endl;
			}
			else
			{
				cout<<"No"<<endl;
			}

		}//while
		cout<<endl;
	}//while
    //system("pause") ;
	return 0;
}



Run IDUserProblemResultMemoryTimeLanguageCode LengthSubmit Time
12373669niuliguo1363Accepted732K610MSG++1363B2013-12-12 16:33:01

注明出处:http://blog.youkuaiyun.com/lavorange/article/details/17284799

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值