数球问题 MST

· · 个人记录

link。

Solution

太难了。

其实你需要知道每个点的奇偶性,那你就需要知道所有前缀的奇偶性。然后你要把这些给拼起来。

显然的,如果你知道了两个区间 [1, 2] 和 [3, 4] 那你就可以知道 [1, 4] 了。或者说你知道了 [1, 4] 和 [3, 4] 那你就可以知道 [1, 2] 了。

考虑这样一种连边:对于每个询问,l 与 r + 1 之间连一条边权为 w 的边。(或者是 [0, l) 与 [0, r] 之间连边。)

然后现在我需要知道所有的前缀,那我需要把这些线段都拼起来,跑一个 MST 即为所求。

Code

#include <bits/stdc++.h>

using namespace std;

using i64 = long long;

const int N = 4e6 + 10, inf = 0x3f3f3f3f;

int n, p[N], cnt;
struct edge { int u, v, w; } e[N];

int fifa(int x) { return p[x] == x ? x : p[x] = fifa(p[x]); }

int main()
{
    cin.tie(0)->ios::sync_with_stdio(false);
    cin >> n;
    for (int i = 1; i <= n; i++) {
        for (int j = i; j <= n; j++) {
            int x; cin >> x;
            e[++cnt] = { i, j + 1, x };
        } 
    }
    for (int i = 1; i <= n + 1; i++) p[i] = i;
    sort (e + 1, e + cnt + 1, [&](edge x, edge y) { return x.w < y.w; });
    i64 ans = 0;
    for (int i = 1; i <= cnt; i++) {
        int u = fifa(e[i].u), v = fifa(e[i].v);
        if (u == v) continue;
        ans += e[i].w;
        p[u] = v;
    }
    cout << ans;
    return 0;
}