[kruskal][Trie] Codeforces 888G Xor-MST

题目描述

You are given a complete undirected graph with nn vertices. A number a_{i}ai is assigned to each vertex, and the weight of an edge between vertices ii and jj is equal to a_{i}xora_{j}aixoraj .

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

输入输出格式

输入格式:

The first line contains nn ( 1<=n<=2000001<=n<=200000 ) — the number of vertices in the graph.

The second line contains nn integers a_{1}a1 , a_{2}a2 , ..., a_{n}an ( 0<=a_{i}<2^{30}0<=ai<230 ) — the numbers assigned to the vertices.

输出格式:

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

输入输出样例

输入样例#1: 
5
1 2 3 4 5
输出样例#1: 
8
输入样例#2:
4
1 2 3 4
输出样例#2:
8

题解

  • 先考虑如何处理异或,比较常规的做法就是建一棵Trie,求最小生成树,则用Kruskal
  • 考虑dfs到一个点x,如果它有左右两个儿子,注意左右两子树已经递归地被连通成一个连通块了,那么还需要一条边连接它的左右两棵子树对应的连通块
  • 我们可以暴力地找这条边,同时从左右两边走下去,如果能同时走左边就同时走左边,能同时走右边就同时走右边,都能就都走
  • 这样的话时间似乎会超时,但根据启发式合并的思想,每次连边的复杂度等于 树的深度×小的子树的大小,故DFS+连边总时间不超过O(nlog^2n)

代码

 1 #include <cstdio>
 2 #include <cstring>
 3 #include <iostream>
 4 #define ll long long
 5 using namespace std;
 6 int const N=30,M=2e5+1;
 7 struct tree{ int son[2],d; }t[N*M]; 
 8 int n;
 9 ll ans,root,tot,r,mi[N],a[M];
10 void merge(int x,int y,ll k)
11 {
12     if (t[x].d==N) { r=min(r,k); return; }
13     bool flag=false;
14     for (int i=0;i<=1;i++) if (t[x].son[i]&&t[y].son[i]) merge(t[x].son[i],t[y].son[i],k),flag=true;
15     if (!flag)
16     {
17         if (t[x].son[0]&&t[y].son[1]) merge(t[x].son[0],t[y].son[1],k+mi[N-t[x].d-1]); else merge(t[x].son[1],t[y].son[0],k+mi[N-t[x].d-1]);
18     }
19 }
20 void dfs(int x)
21 {
22     if (!x||t[x].d==N) return;
23     for (int i=0;i<=1;i++) dfs(t[x].son[i]);
24     if (t[x].son[0]&&t[x].son[1]) r=2e9,merge(t[x].son[0],t[x].son[1],mi[N-t[x].d-1]),ans+=r;
25 }
26 int main()
27 {
28     mi[0]=1; for (int i=1;i<N;i++) mi[i]=mi[i-1]*2;
29     scanf("%d",&n),root=tot=1;
30     for (int i=1,x;i<=n;i++)
31     {
32         scanf("%lld",&a[i]),x=root;
33         for (int j=0;j<N;j++)
34         {
35             int r=((mi[N-j-1]&a[i])>0);
36             if (!t[x].son[r]) t[x].son[r]=++tot,t[tot].d=t[x].d+1;
37             x=t[x].son[r];
38         }
39     }
40     dfs(1),printf("%lld",ans);
41 }
原文地址:https://www.cnblogs.com/Comfortable/p/11200302.html