POJ1363 Rails(栈)

本文介绍了一种算法问题,即给定火车进出站序列,判断该序列是否合法。通过模拟火车进出栈的过程,使用两种方法(一种直接操作数组,另一种使用栈)实现,并给出AC代码。

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

题目链接:点击打开链接


给你一个n,接下来一行是n个数字,代表出火车站的顺序,进火车站的顺序是1-n,问你是否可以按照给定的顺序出火车站。


火车站好比一个栈,火车进站代表入栈,火车出站代表出栈,可以模拟这个过程来判断是否符合题意。


不用stack的写法:

        对读入数据后的for循环进行分析,每一个cnt代表是火车的序号,火车每出站和入站匹配时就匹配下一列火车,为-1时说明所有火

车都匹配完成,每次匹配失败时i++,表示当前火车没有出火车站,最后判断j是否为n即火车是否全部出站。


AC代码:

#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
using namespace std;
const int MAXN = 1005;
int n, out[MAXN], in[MAXN];
int main(int argc, char const *argv[])
{
	while(scanf("%d", &n) != EOF && n) {
		int x;
		while(scanf("%d", &x) != EOF && x) {
			out[0] = x;
			for(int i = 1; i < n; ++i)
				scanf("%d", &out[i]);
			int j = 0, cnt = 1;
			for(int i = 0; cnt <= n; ) {
				in[i] = cnt;
				while(in[i] == out[j]) {
					i--, j++;
					if(i == -1) break;
				}
				i++, cnt++;
			}
			if(j == n) printf("Yes\n");
			else printf("No\n");
		} 
		printf("\n");
	}
	return 0;
}</span>


用stack的写法:

与上面相同,每次i入栈,代表火车进站,匹配成功且栈不为空时就弹出,也就是火车出站,最后也是通过j是否等于n判断火车是

否全部出站,最后还要初始化,否则会wa,因为下一次可能会继续匹配下去。。


AC代码:

#include "iostream"
#include "cstdio"
#include "cstring"
#include "algorithm"
#include "stack"
using namespace std;
const int MAXN = 1005;
int n, out[MAXN];
stack<int> in;
int main(int argc, char const *argv[])
{
	while(scanf("%d", &n) != EOF && n) {
		int x;
		while(scanf("%d", &x) != EOF && x) {
			out[0] = x;
			for(int i = 1; i < n; ++i)
				scanf("%d", &out[i]);
			int j = 0;
			for(int i = 1; i <= n; ++i) {
				in.push(i);
				while(!in.empty() && in.top() == out[j]) {
					in.pop();
					j++;
				}
			}
			if(j == n) printf("Yes\n");
			else printf("No\n");
			memset(out, 0, sizeof(out));
		} 
		printf("\n");
	}
	return 0;
}</span>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值