清华数据结构 PA题目--列车调度(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”.

Example 1
Input

5 2
1 2 3 5 4
Output

push
pop
push
pop
push
pop
push
push
pop
pop
Example 2
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

95分代码

#include <cstdio>
#include <cstring>
int out[1600010];
char print[3200010][5];
int stack[1600010];
int sHead = 0;

void push( int n )
{
    stack[++sHead] = n;
}

int top()
{
    return stack[sHead];
}

int pop()
{
    return stack[sHead--];
}

int main()
{
    int m, n;
    int op = 0;
    scanf( "%d%d", &n, &m );

    int i;
    for (i = 1; i <= n; i++)
        scanf( "%d", &out[i] );
    int j = 1;
    i = 1;
    while (i <= n)
    {
        if (j <= n && sHead <= m && out[i] >= j)
        {
            push( j++ );
            strcpy( print[op++], "push" );
        }
        else
        {
            if (out[i] == top())
            {
                pop();
                strcpy( print[op++], "pop" );
                i++;
            }
            else
            {
                puts( "No" );
                return 0;
            }
        }
    }

    for (int k = 0; k < op; k++)
    {
        puts( print[k] );
    }
}
  • 7
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值