科技笔记:完全图生成树 Boruvka

· · 科技·工程

对于一类完全图最小生成树问题,边权以点权计算得,则有较大概率为 Boruvka 题。 \\ Boruvka 的核心是计算目前连通块到其他连通块的最短边并连边。则每次连通块数量减半,\mathcal O(m \log n)。然而在特殊点权题中不需要用 \mathcal O(m) 去计算最小边,而是可以 DS 维护计算,于是就有了完全图特殊边权的一种做法。

Problem CF888G Xor-MST

有 n 个点,点权为 a_i,边的权值为 a_i \operatorname{xor} a_j,求最小生成树。2 \le n \le 2\times10^5,0 \le a_i \lt 2 ^ {30}。

Solution

看到完全图,想到 Boruvka,看到异或,想到 Trie。 现在考虑如何快速计算一个连通块到其他连通块的边权最小值。将所有 a_i 插入一只 Trie。将在该连通块的点权删去后对于该点权计算最小异或和,连好边后再将点权重新加回去。\mathcal O(n \log n \log V)。

const int N = 2e5 + 10;

int n, w[N];
int p[N]; int tr[N * 30][2], idx;
int sz[N * 30], ed[N * 30];
vector<int> id;
vector<int> c[N];
int cz[N]; LL res;
bool st[N];

void ins(int x, int pw) { 
    int p = 0; sz[p] ++ ;
    for (int i = 29; i >= 0; i -- ) {
        if (!tr[p][x >> i & 1]) tr[p][x >> i & 1] = ++ idx;
        p = tr[p][x >> i & 1]; sz[p] ++ ;  
    } ed[p] = pw;
}
void del(int x) { int p = 0; sz[p] -- ;
    for (int i = 29; i >= 0; i -- ) sz[(p = tr[p][x >> i & 1])] -- ;
}
int find(int x) {
    if (p[x] != x) p[x] = find(p[x]);
    return p[x];
}
PII qry(int x) {
    int res = 0, p = 0;
    for (int i = 29; i >= 0; i -- ) {
        if (tr[p][x >> i & 1] && sz[tr[p][x >> i & 1]]) p = tr[p][x >> i & 1];
        else p = tr[p][!(x >> i & 1)], res |= (1 << i);
    } return {res, ed[p]};
}

void mian() {
    scanf("%d", &n); for (int i = 1; i <= n; i ++ ) scanf("%d", &w[i]);
    sort(w + 1, w + 1 + n); n = unique(w + 1, w + 1 + n) - w - 1;
    for (int i = 1; i <= n; i ++ ) { p[i] = i; ins(w[i], i); }
    while (1) {
        fill(st + 1, st + 1 + n, 0); int s = 0;
        for (int i = 1; i <= n; i ++ ) c[find(i)].push_back(i);
        for (int i = 1; i <= n; i ++ ) {
            if (p[i] != i || st[i]) continue ; cz[i] = c[i].size();
            for (int j : c[i]) del(w[j]); s ++ ;
            int pos = 0, minv = (1LL << 31) - 1;
            for (int j : c[i]) {
                PII cnt = qry(w[j]);
                if (cnt.fi < minv) minv = cnt.fi, pos = cnt.se;
            } if (pos) res += minv, p[i] = find(pos), st[i] = st[find(pos)] = 1; 
            for (int j : c[i]) ins(w[j], j);
        }
        for (int i = 1; i <= n; i ++ ) c[i].clear();
        if (s == 1) break ; 
    } printf("%lld\n", res);
}