清华数据结构PA4——列车调度(Train)

题目:https://dsa.cs.tsinghua.edu.cn/oj/problem.shtml?id=1145

比较简单的题目,其实就是判断是否是一个合法的栈混洗。而判断的最快方法就是直接模拟入栈出栈的过程。

#include <stdio.h>
#define MAX 1600001
int B[MAX];
int S[MAX];
int result[2*MAX];
int main()
{
	int topS = 0;
	int topR = 0;
	int n, m ;
	int key = 1;
	scanf("%d %d", &n, &m);
	for (int i = 0 ; i < n; i++)
	{
		scanf("%d", &B[i]);
	}
	for (int i = 1, j = 0; i <= n; i++)
	{
		if (topS<m)
		{
			S[topS++] = i;
			result[topR++] = 0;
		}
		else
		{
			key = 0;
			break;
		}
		if (i==B[j])
		{
			j++;
			S[--topS] = 0;
			result[topR++] = 1;
		}
		while (topS>0&&B[j]==S[topS-1])
		{
			j++;
			S[--topS] = 0;
			result[topR++] = 1;
		}
	}
	if (topS != 0|| key == 0)
	{
		printf("No\n");
	}
	else
	{
		for (int i = 0; i < topR; i++)
		{
			if (result[i] == 1)
			{
				printf("pop\n");
			}
			else if (result[i] == 0)
			{
				printf("push\n");
			}
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值