跳到正文

题解

CF888G 题解

rainygame约 5 分钟
原文
文章信息与版本

文章信息

发布
2024年8月6日
收录
2026年6月7日
更新
2026年11月10日
篇幅
约 5 分钟
获赞
6
题目
CF888G

版本

  1. v1当前

看到完全图最小生成树想到 Boruvka。

每一轮合并时需要维护每个连通块的最小出边,异或最小值可以用 01-Trie 求出。

大概思路是对于每一个连通块,先把这个连通块内的 aia_i 从 01-Trie 中删除,然后再对于它们找出异或最小值并加上这条边,最后再加回 01-Trie。

01-Trie 的删除可以对于每个结点维护 cnt 表示这里面有多少个数 aia_i,删除时路径上的 cnt 减一,查询时只走 cnt 非零的结点。

C++
#include <bits/stdc++.h>
using namespace std;
#define int long long
#define MAXN 200001
#define MAXK 30

int n, ans;
int a[MAXN], f[MAXN]; bool vis[MAXN];
int find(int x){return f[x] == x ? x : f[x] = find(f[x]);}
vector<int> vid[MAXN];

namespace Trie{
    struct Node{int s[2], cnt, id;};
    vector<Node> tr(1, {{0, 0}, 0});
    void ins(int x, int id){
        int now(0);
        for (int i(MAXK-1); ~i; --i){
            if (!tr[now].s[(x>>i)&1]){
                tr[now].s[(x>>i)&1] = tr.size();
                tr.push_back({{0, 0}, 0});
            }
            ++tr[now=tr[now].s[(x>>i)&1]].cnt;
        }
        tr[now].id = id;
    }
    void del(int x){
        for (int i(MAXK-1), now(0); ~i; --i) --tr[now=tr[now].s[(x>>i)&1]].cnt;
    }
    pair<int, int> query(int x){
        int res(0), now(0);
        for (int i(MAXK-1); ~i; --i){
            if (!tr[now].s[(x>>i)&1] || !tr[tr[now].s[(x>>i)&1]].cnt){
                now = tr[now].s[!((x>>i)&1)];
                res += 1<<i;
            }else now = tr[now].s[(x>>i)&1];
        }
        return {res, tr[now].id};
    }
}

void boruvka(){
    iota(f+1, f+n+1, 1);
    while (true){
        set<int> id; for (int i(1); i<=n; ++i) id.insert(find(i));
        // cout << id.size() << '\n';
        if (id.size() == 1) return;
        for (int i(1); i<=n; ++i) vid[find(i)].push_back(i);
        for (auto i: id) if (!vis[i]){
            for (auto j: vid[find(i)]) Trie::del(a[j]);
            pair<int, int> res(INT_MAX, 0);
            for (auto j: vid[find(i)]){
                auto p(Trie::query(a[j]));
                if (p.first < res.first) res = p;
            }
            for (auto j: vid[find(i)]) Trie::ins(a[j], j);
            f[find(i)] = find(res.second); vis[find(res.second)] = vis[i] = 1;
            ans += res.first;
            // cout << res.first << ' ' << res.second << '\n';
        }
        for (auto i: id) vis[i] = 0;
        for (int i(1); i<=n; ++i) vid[i].clear();
    }
}

signed main(){
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);

    cin >> n; for (int i(1); i<=n; ++i) cin >> a[i];
    sort(a+1, a+n+1); n = unique(a+1, a+n+1)-(a+1);
    for (int i(1); i<=n; ++i) Trie::ins(a[i], i);
    boruvka(); cout << ans;

    return 0;
}
原文