POJ1363 火车出入站问题,用stack( 栈 )模拟地铁出站。

题目链接:

链接 POJ 1363

题意:

一列火车在如车站前,车厢入栈时默认是1,2,3,4,5…到n这样排列的。以0 为一块与一块的分界线。0 0表示结束。
输入想要出站后看到的排列,看通过在车站里进行入站,出站操作能否达到自己想要的排列。

stack是一个先进后出,函数正好可以满足条件。

输入样例:

5
1 2 3 4 5
5 4 1 2 3
0
6
6 5 4 3 2 1
0
0

输出样例:

Yes
No

Yes

题解以及代码思路如下:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<stack>
#include<math.h>
#include<algorithm> 
#include<iostream>
using namespace std;
int main() {
	int n;//车厢的个数
	int outbound[2000];//储存出站时想怎样排列的数组。
	while(scanf("%d",&n)&&n) {
		stack<int> s;//车站,用于进行比对。
		cin>>outbound[1];//从第一位开始。
		while(outbound[1]) {//为0时进行下一块。
			for(int i=2; i<=n; i++) cin>>outbound[i];
			int count=1;//用于记录栈中成功比对的个数 + 1 ;
			for(int i=1; i<=n; i++) {
				s.push(i);//入栈前的车厢排列;
				while(!s.empty()&&outbound[count]==s.top()) {//和最上边的进行比对。
					s.pop();//比对成功最上边的一位弹出;
					count++;
				}
			}
			if(count-1==n) cout<<"Yes"<<endl;
			else cout<<"No"<<endl;
			memset(outbound,0,sizeof(outbound));
			cin>>outbound[1];
		}
		cout<<endl;
	}
	return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值