b747困難

同色同步的雙人換位

在有序頂點對上求最短換位,並用終點距離選字典序最小首步。

解題思路

狀態 (u,v) 保留兩人的標籤。枚舉兩條同色邊 u→x、v→y,排除 x=y 的碰面及 x=v 且 y=u 的相向穿越。每一步恰好一秒,所以在這張乘積圖從目標 (t,s) 做 BFS 可得所有狀態到目標的最短秒數。

原圖無向,合法同步移動的反向仍同色,且相同兩種禁止條件也對稱,因此反向 BFS 可直接使用相同鄰接生成器。起點距離為 D 時,最短方案首步必滿足距離 D-1;枚舉其中字典序最小的 (x,y) 即為答案,不需要保存所有完整路徑。

時間 O(n²+m²),空間 O(n²+m);所有有序頂點對的鄰邊乘積總和不超過 (2m)²,n≤40、m≤300。Python 輸入 token O(m)。

Step-by-step animation

逐步推演(例子條件見步驟說明)

回報動畫錯誤
步驟 1 / 3

設置目標

四環 1–2–3–4–1,從 (1,3) 換到 (3,1)。

(3,1)
距離
0

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
using ll = long long;
int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, m, s, t;
    cin >> n >> m >> s >> t;
    --s;
    --t;
    vector<array<vector<int>, 2>> g(n);
    while (m--) {
        int u, v, c;
        cin >> u >> v >> c;
        --u;
        --v;
        g[u][c].push_back(v);
        g[v][c].push_back(u);
    }
    vector<int> d(n * n, -1);
    queue<pair<int, int>> q;
    d[t * n + s] = 0;
    q.push({t, s});
    auto nexts = [&](int u, int v, auto f) {
        for (int c = 0; c < 2; c++)
            for (int x : g[u][c])
                for (int y : g[v][c])
                    if (x != y && !(x == v && y == u))
                        f(x, y);
    };
    while (!q.empty()) {
        auto [u, v] = q.front();
        q.pop();
        nexts(u, v, [&](int x, int y) {
            if (d[x * n + y] < 0) {
                d[x * n + y] = d[u * n + v] + 1;
                q.push({x, y});
            }
        });
    }
    int D = d[s * n + t];
    if (D < 0) {
        cout << "-1 0 0\n";
        return 0;
    }
    pair<int, int> a = {n, n};
    nexts(s, t, [&](int x, int y) {
        if (d[x * n + y] == D - 1)
            a = min(a, make_pair(x, y));
    });
    cout << D << ' ' << a.first + 1 << ' ' << a.second + 1 << '\n';
}

先試著自己完成,再切換語言比對解法。參考程式可複製到題目編輯器。

更多