Educational Codeforces Round 32 G. Xor-MST

来源:互联网 发布:mysql 查询替换字符串 编辑:程序博客网 时间:2024/05/16 03:50

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;}
原创粉丝点击