Educational Codeforces Round 32 G. Xor-MST

本文探讨了一个特定的图论问题:给定一个完全无向图,每个顶点赋有一个数值,边权为两个顶点数值的XOR值,目标是最小生成树的总权重。通过构建二叉树并采用分治策略,文章提出了一种有效求解该问题的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

G. Xor-MST
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard output
You are given a complete undirected graph with n vertices. A number ai is assigned to each vertex, and the weight of an edge between vertices i and j is equal to ai xor aj.

Calculate the weight of the minimum spanning tree in this graph.

Input
The first line contains n (1 ≤ n ≤ 200000) — the number of vertices in the graph.

The second line contains n integers a1, a2, …, an (0 ≤ ai < 230) — the numbers assigned to the vertices.

Output
Print one number — the weight of the minimum spanning tree in the graph.

Examples
input
5
1 2 3 4 5
output
8
input
4
1 2 3 4
output
8

这里mark一个复杂度,对与一个深度不超过log的二叉树,对每一层左右儿子合并的复杂度事log。
对于这一题,建一颗二叉树,两两差值最小的点连接,这样的点肯定是高位尽可能相同,低位不同,然后以不相同的低位看成一个整体,然后让它和高位的另一个子树合并,合并的方法就是将一个子树的值建一个二叉树,然后暴力枚举另一个子树的值,在建好的二叉树上跑,找出最小值。复杂度大概是nloglog

#include<bits/stdc++.h>
using namespace std;
const int N = 2e5+7,M =N*35;
int nex[M][2];
int tot,a[N];
long long ans = 0;

void ins(int x){
    int now = 0;
    for(int i = 29;i >= 0;i --){
        int t = (x>>i)&1;
        if(nex[now][t] == 0) nex[now][t] = ++tot;
        now = nex[now][t];
    }
}

int ask(int x){
    int ret = 0;
    int now = 0;
    for(int i = 29;i >= 0;i --){
        int t = (x>>i)&1;
        if(nex[now][t]) now = nex[now][t];
        else now = nex[now][t^1],ret |= (1<<i);
    }
    return ret;
}

void dfs(int l,int r,int dep){
    if(dep == -1||l >= r) return ;
    int mid = l-1;
    while(mid < r &&(a[mid+1]>>dep&1)==0) mid ++;
    dfs(l,mid,dep-1),dfs(mid+1,r,dep-1);
    if(mid == l-1 || mid == r) return ;
    for(int i = l;i <= mid;i ++){
        ins(a[i]);
    }
    int ret=~0U>>1;
    for(int i = mid+1;i <= r;i ++){
        ret = min(ret,ask(a[i]));
    }
    ans += ret;
    for(int i = 0;i <= tot;i ++){
        nex[i][0] = nex[i][1] = 0;
    }
    tot = 0;
}

int main(){
    int n;
    cin >> n;
    for(int i = 1;i <= n;i ++) scanf("%d",&a[i]);
    sort(a+1,a+n+1);
    dfs(1,n,29);
    cout << ans << endl;
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值