P1139 题解

· · 题解

搜索模板

不难想到,至少要调动 n 次,最多要调动 3n 次。

使用迭代加深搜索,从小到大枚举每次调动次数 lim,按最小字典序搜索。即 A 到 B,A 到 C,A 到 D,B 到 C,B 到 D,C 到 D。

找到答案输出并结束程序,枚举完 lim 还没找到答案输出 NO。

剪枝

  1. 如果剩余步数不足以将所有火车调度到 D,返回。

  2. 如果 D 点的火车顺序不合要求,返回,反正再搜下去也是错的。

  3. 火车到达 C 后,就只能等待进入 D 点,因此新火车在进入站 C 时,最终顺序不得被打乱,即,新火车排名要更小。

  4. 显然如果火车能直接跳到 D,那就别浪费步数,直接跳到 D,此时没有再尝试别的车站的需要。注意,可能存在两种决策方式,决策后结果相同,花费步数也相同。如果先将合法火车调度到 D,在进行其他调度,字典序更大;如果先进行其他调度,再调度合法火车,字典序更小。因此,在进行此剪枝时,要将字典序最小的方案先搜一遍。但如果已经搜到了合法火车所在站点,就直接进行此剪枝,返回。因为之后不管怎么调度,都要先等合法火车进 D 站,此时将合法火车调度到其他站点,不仅降低之后操作的灵活性,还浪费步数。

  5. 从 A 跳到 B,再从 B 跳到 C,这明显是在浪费步数,不如直接从 A 跳到 C。因此搜索时,记录一下上一步把节点调度到什么站,这次调度就不要在调度那个站。

经过上述优化,程序跑得飞快。附一下提交记录。

代码

#include <bits/stdc++.h>
#define maxn 31
//using namespace std;
int n, md[maxn], s[4][maxn], cnt[maxn], lim, from[maxn << 2], to[maxn << 2], ans[maxn << 2], Rank[maxn];
char str[maxn];

void dfs(int step, int last) {
    if (s[3][cnt[3]] != md[cnt[3]]) {
        return;
    }
    if (lim - step + 1 < n - cnt[3]) {
        return;
    }
    if (step == lim + 1 && !(cnt[0] + cnt[1] + cnt[2])) {
        for (int i = 1; i < step; ++i) {
            printf("%c %c %c\n", ans[i] + 'a' - 1, from[i] + 'A', to[i] + 'A');
        }
        exit(0);
    }
    if (step > lim) {
        return;
    }
    for (int i = 0; i <= 2; ++i) {
        if (i == last) {
            continue;
        }
        if (s[i][cnt[i]] == md[cnt[3] + 1]) {
            int tmp = s[i][cnt[i]--];
            ans[step] = s[3][++cnt[3]] = tmp;
            from[step] = i, to[step] = 3;
            dfs(step + 1, 3);
            s[i][++cnt[i]] = tmp, --cnt[3];
            return;
        }
        for (int j = i + 1; j <= 3 && cnt[i]; ++j) {
            if (j == 2) {
                if (cnt[2] && Rank[s[i][cnt[i]]] >= Rank[s[2][cnt[2]]]) {
                    continue;
                }
            }
            int tmp = s[i][cnt[i]--];
            s[j][++cnt[j]] = ans[step] = tmp;
            from[step] = i;
            to[step] = j;
            dfs(step + 1, j);
            s[i][++cnt[i]] = tmp, --cnt[j];
        }
    }
}

int main() {
    scanf("%d%s", &n, str + 1);
    for (int i = 1; i <= n; ++i) {
        md[n - i + 1] = str[i] - 'a' + 1, s[0][++cnt[0]] = i, Rank[md[n - i + 1]] = n - i + 1;
    }
    for (lim = n; lim <= n * 3; ++lim) {
        dfs(1, -1);
    }
    puts("NO");
    return 0;
}