Tsinghua mooc 数据结构上 列车调度(Train) 栈混洗

描述
某列车调度站的铁道联接结构如Figure 1所示

这里写图片描述

其中,A为入口,B为出口,S为中转盲端。所有铁道均为单轨单向式:列车行驶的方向只能是从A到S,再从S到B;另外,不允许超车。因为车厢可在S中驻留,所以它们从B端驶出的次序,可能与从A端驶入的次序不同。不过S的容量有限,同时驻留的车厢不得超过m节。
设某列车由编号依次为{1, 2, …, n}的n节车厢组成。调度员希望知道,按照以上交通规则,这些车厢能否以{a1, a2, …, an}的次序,重新排列后从B端驶出。如果可行,应该以怎样的次序操作?

输入
共两行。

第一行为两个整数n,m。

第二行为以空格分隔的n个整数,保证为{1, 2, …, n}的一个排列,表示待判断可行性的驶出序列{a1,a2,…,an}。

输出
若驶出序列可行,则输出操作序列,其中push表示车厢从A进入S,pop表示车厢从S进入B,每个操作占一行。

若不可行,则输出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

限制
1 ≤ n ≤ 1,600,000

0 ≤ m ≤ 1,600,000

时间:2 sec

空间:256 MB

代码如下

#include<cstdio>
#include<string.h>
const int maxn = 16e5 + 5;

struct stack
{
    int n = 0;
    int ss[maxn];

    void push(int a)
    {
        n++;
        ss[n] = a;
    }
    void pop()
    {
        n--;
    }
    int top()
    {
        return ss[n];
    }
    bool empty()
    {
        if(n == 0)return true;
        else return false;
    }
    int size()
    {
        return n;
    }
};

stack  a;
stack  s;
stack  b;
bool way[maxn];
int total[maxn];
int main()
{
    int m, n;
    scanf("%d%d", &n, &m);
    for(int i = n; i >= 1; i--)
    {
        a.push(i);
    }
    for(int i = 0; i < n; i++)
        scanf("%d", &total[i]);
    int j = 0, k = 0;
    bool y = false;
    while(!y)
    {
        if(k == n){y = true; break;}
        if(s.empty())
        {
            s.push(a.top());
            a.pop();
            way[j] = true;
        }
        else if(total[k] == s.top())
        {
            b.push(s.top());
            s.pop();
            k++;
            way[j] = false;
        }
        else if(!a.empty())
        {
            s.push(a.top());
            a.pop();
            way[j] = true;
        }
        else
        {
            printf("No\n");
            break;
        }
        if(s.size() > m)
        {
            printf("No\n");
            break;
        }
        j++;
    }
    if(y)
    {
        for(int i = 0; i < j; i++)
        {
            if(way[i]) printf("push\n");
            else printf("pop\n");
        }
    }
    return 0;
}

最终结果


Case No.    Result  Time(ms)    Memory(KB)
1   Accepted    0   39000
2   Accepted    0   39000
3   Accepted    0   39000
4   Accepted    0   39000
5   Accepted    0   39000
6   Accepted    0   39000
7   Accepted    0   39000
8   Accepted    0   39000
9   Accepted    0   39000
10  Accepted    0   39000
11  Accepted    4   39000
12  Accepted    8   39000
13  Accepted    20  39000
14  Accepted    40  39000
15  Accepted    32  39000
16  Accepted    12  39000
17  Accepted    96  39000
18  Wrong Answer    292 39000
19  Wrong Answer    352 39000
20  Wrong Answer    328 39000

简单模拟了stack操作,有点费空间,遗憾的是最后三个用例不能过,目前没想到原因,希望有大佬可以帮我看下哈,谢谢。

猜你喜欢

转载自blog.csdn.net/wbl1970353515/article/details/82668854