b068困難

105 高雄市資訊學科能力競賽(2016)|學園生活

在所有偏好點間求最近的一對。

解題思路

把所有偏好點以距離0同時放入Dijkstra,另記每個節點歸屬的最近來源owner。未被任何來源抵達的點不處理。

最短路完成後,掃描每條兩端owner不同的邊(u,v,w),候選距離為dist[u]+w+dist[v]。這條路串接兩個不同來源,所以每個候選都對應一條合法來源間路徑。

最近兩來源的最短路沿途必跨越兩個來源分區,跨區邊候選不大於該最短距離,因此取候選最小值恰為答案。若沒有跨區邊則各來源互不相連,輸出zombie。

時間O((N+M)log N)次大整數操作,圖、距離、堆O(N+M),Python批次輸入另O(N+M);數字位元成本依輸入長度。

Step-by-step animation

多來源最短路的分區邊界|鏈1–2–3,權重4,7,來源1與3。

回報動畫錯誤
步驟 1 / 3

分區

鏈1–2–3,權重4,7,來源1與3。

1:距0
2:距4屬1
3:距0
來源
1,3

Reference solution

回報程式錯誤

完整程式

#include <bits/stdc++.h>
using namespace std;
#include <boost/multiprecision/cpp_int.hpp>
using boost::multiprecision::cpp_int;
struct E {
    int u, v;
    cpp_int w;
};
int main() {
    int n, m, k;
    cin >> n >> m >> k;
    vector<E> e(m);
    vector<vector<pair<int, int>>> g(n);
    for (int i = 0; i < m; i++) {
        cin >> e[i].u >> e[i].v >> e[i].w;
        --e[i].u;
        --e[i].v;
        g[e[i].u].push_back({e[i].v, i});
        g[e[i].v].push_back({e[i].u, i});
    }
    vector<cpp_int> d(n);
    vector<int> o(n, -1);
    using P = pair<cpp_int, int>;
    priority_queue<P, vector<P>, greater<P>> q;
    while (k--) {
        int s;
        cin >> s;
        --s;
        o[s] = s;
        d[s] = 0;
        q.push({0, s});
    }
    while (q.size()) {
        auto [w, u] = q.top();
        q.pop();
        if (w != d[u])
            continue;
        for (auto [v, i] : g[u]) {
            cpp_int x = w + e[i].w;
            if (o[v] < 0 || x < d[v]) {
                d[v] = x;
                o[v] = o[u];
                q.push({x, v});
            }
        }
    }
    cpp_int ans = 0;
    bool found = false;
    for (auto &x : e)
        if (o[x.u] >= 0 && o[x.v] >= 0 && o[x.u] != o[x.v]) {
            cpp_int v = d[x.u] + x.w + d[x.v];
            if (!found || v < ans) {
                ans = v;
                found = true;
            }
        }
    if (found)
        cout << ans << "\n";
    else
        cout << "zombie\n";
}

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

更多