数据结构(上)(自主模式) 列车调度(Train)

列车调度(Train)
Description
Figure 1 shows the structure of a station for train dispatching.

在这里插入图片描述

Figure 1

In this station, A is the entrance for each train and B is the exit. S is the transfer end. All single tracks are one-way, which means that the train can enter the station from A to S, and pull out from S to B. Note that the overtaking is not allowed. Because the compartments can reside in S, the order that they pull out at B may differ from that they enter at A. However, because of the limited capacity of S, no more that m compartments can reside at S simultaneously.

Assume that a train consist of n compartments labeled {1, 2, …, n}. A dispatcher wants to know whether these compartments can pull out at B in the order of {a1, a2, …, an} (a sequence). If can, in what order he should operate it?

Input
Two lines:

1st line: two integers n and m;

2nd line: n integers separated by spaces, which is a permutation of {1, 2, …, n}. This is a compartment sequence that is to be judged regarding the feasibility.

Output
If the sequence is feasible, output the sequence. “Push” means one compartment goes from A to S, while “pop” means one compartment goes from S to B. Each operation takes up one line.

If the sequence is infeasible, output a “no”.

Input

5 2
1 2 3 5 4

Output

push
pop
push
pop
push
pop
push
push
pop
pop

Input

5 5
3 1 2 4 5

Output

No

Restrictions
1 <= n <= 1,600,000

0 <= m <= 1,600,000

Time: 2 sec

Memory: 256 MB

题意:给你一个从1到n的序列,问你是否能通过入栈和出栈操作将1-n按顺序进入的序列变为目标序列。

思路:不能用STL,直接手写栈模拟操作。给目标序列一个指针,如果栈顶元素等于指针指向的目标序列的值,则出栈,否则就下一个数入栈。如果期间栈内元素超过m或者最后所有元素没有完全排列,就是no,否则按顺序输出答案

#include<cstdio>
#include<iostream>
using namespace std;
int a[1600005];
int stack[1600005];
int cnt=0;
void push(int x){
	stack[cnt++]=x;
}
void pop(){
	if(cnt==0)
		return ;
	stack[--cnt]=0;
}
int top(){
	if(cnt==0)
		return -1;
	return stack[cnt-1];
}
int ans[3200005];
int main(){
	int n,m;
	scanf("%d%d",&n,&m);
	int now=1;
	int cct=0;
	int ok=1;
	for(int i=1;i<=n;++i){
		scanf("%d",&a[i]);
	//	cout<<cnt<<endl;
	
	}
	for(int i=1;i<=n;i++){
		if(i==a[now]){
			ans[cct++]=1;
			ans[cct++]=0;
			now++;
		}
		else{
			push(i);
			ans[cct++]=1;
		}
		if(cnt>=m)
			ok=0;
		while(top()==a[now]){
			pop();
			ans[cct++]=0;
			now++;
		}
	}
		
//	cout<<now<<endl;
	if(now<=n)
		ok=0;
	if(!ok){
		printf("No\n");
		return 0;
	}
	for(int i=0;i<cct;i++){
		if(ans[i]==1)
			printf("push\n");
		else
			printf("pop\n");
	}
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值