UVA 514Rails(栈的应用)

Rails

题意:入栈顺序为1到n,问你出栈顺序是否满足要求,例如有5列车,出栈顺序54321可以,但54123不行。
用栈模拟一下即可
#include<bits/stdc++.h>
using namespace std;
const int N = 1e3 + 10;

int n;
int a[N];
stack<int> s, t;

int main()
{
	while(cin >> n){
		if(n == 0){
			break;
		}
		int m;
		while(cin >> m){
			if(m == 0){
				break;
			}
			while(!s.empty())
				s.pop();
			a[1] = m;
			for (int i = 2; i <= n; i++){
				cin >> a[i];
			}
			int start = 1, end = 1;			//start代表入站的顺序,end代表出站的顺序
			int flag = 1;
			while(end <= n){
				if(start == a[end]){			//从入站进入一节,直接出战
					start++;
					end++;
				}else if(!s.empty() && s.top() == a[end]){		//从中间站台出站
					s.pop();
					end++;
				}else if(start <= n){			//当前的出战节点和入站,中间站,都不一样,从入站进入一节,后面接着判断
					s.push(start++);
				}else{
					flag = 0;
					break;
				}
			}
			printf("%s\n", flag ? "Yes" : "No");
		}
		cout << endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值