a275困難調價前綴二分・重新計算 MST

TOI 2025/04 潛力組:供給調度

在累積調價下找出最小生成樹成本首次嚴格大於 K 的時刻。

前往題目練習 →回報教學錯誤時間 O((Q + M log M + M α(N)) log(Q+1)),空間 O(N+M+Q);N、M ≤ 10000,Q ≤ 100000。成本總和使用 64 位元。

解題思路

所有維護成本為正,因此最佳連通方案一定可以刪去多餘環邊,成為最小生成樹。某條邊只會漲價,每棵固定樹的成本都不減,故所有樹中的最小成本也不減。『發生前 t 次調價後 MST > K』具單調性,可以二分首次成立的 t。

每次判定都複製初始成本,套用前 t 次調價,再用升序 Kruskal 求 MST;不要在二分各回合繼續累加上一回合的成本。先判斷 t=0,再判斷 t=Q,分別處理答案 0 與 −1,其他情況才二分 1 到 Q。即使原 MST 的邊漲價後被替換,重新計算也能正確反映最佳方案。

Step-by-step animation

範例:K=6,依序調高三條邊

回報動畫錯誤
步驟 1 / 3

尚未調價

成本為 2、6、3,MST 選 0—1 與 1—2,成本 5。

0—1:2
0—2:6
1—2:3
t
0
MST
5≤6

Reference solution

回報程式錯誤

完整程式

#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <numeric>
using namespace std;
struct Edge {
    int a, b;
    long long w;
};
struct Update {
    int id, delta;
};
int main() {
    int n, m, q;
    cin >> n >> m >> q;
    vector<Edge> edges(m);
    map<pair<int, int>, int> id;
    for (int i = 0; i < m; ++i) {
        cin >> edges[i].a >> edges[i].b >> edges[i].w;
        id[{edges[i].a, edges[i].b}] = i;
    }
    vector<Update> updates(q);
    for (auto &u : updates) {
        int a, b;
        cin >> a >> b >> u.delta;
        if (a > b)
            swap(a, b);
        u.id = id.at({a, b});
    }
    long long k;
    cin >> k;
    auto cost = [&](int t) {
        auto current = edges;
        for (int i = 0; i < t; ++i)
            current[updates[i].id].w += updates[i].delta;
        sort(current.begin(), current.end(),
             [](const Edge &a, const Edge &b) { return a.w < b.w; });
        vector<int> p(n), size(n, 1);
        iota(p.begin(), p.end(), 0);
        auto find = [&](int x) {
            while (x != p[x]) {
                p[x] = p[p[x]];
                x = p[x];
            }
            return x;
        };
        long long sum = 0;
        int count = 0;
        for (auto e : current) {
            int a = find(e.a), b = find(e.b);
            if (a == b)
                continue;
            if (size[a] < size[b])
                swap(a, b);
            p[b] = a;
            size[a] += size[b];
            sum += e.w;
            if (++count == n - 1)
                break;
        }
        return sum;
    };
    if (cost(0) > k) {
        cout << 0 << '\n';
        return 0;
    }
    if (cost(q) <= k) {
        cout << -1 << '\n';
        return 0;
    }
    int lo = 1, hi = q;
    while (lo < hi) {
        int mid = (lo + hi) / 2;
        if (cost(mid) > k)
            hi = mid;
        else
            lo = mid + 1;
    }
    cout << lo << '\n';
}

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

更多