《Xor-MST》 解题报告
又做不出来。。。
我们看到
然后我们如果考虑最小生成树,那么实际上我们每次要先从权值最小的边开始连,也就是说我们从二进制中的最低位开始连边,然后到高位。
那么一开始全部权值为
那么我们考虑用
时间复杂度
每个深度,我们会把整棵树跑一遍,有
这其实类似于
#include<bits/stdc++.h>
typedef long long LL;
using namespace std;
const int NN=6e6+10,MAXN=2e5+10;
const LL inf=(LL)1e18;
int n,cnt;
int ch[NN][2],tot;
int a[MAXN];
void insert(int ii,int x) {
int u=0;
for(int i=30;i>=0;--i) {
bool to;
if((x&(1<<i))) to=1;
else to=0;
if(!ch[u][to]) ch[u][to]=++tot;
u=ch[u][to];
}
}
LL find(int x,int y,int dep) {
if(dep==-1) return 0;
LL res=inf;
if(ch[x][0]&&ch[y][0]) {
res=find(ch[x][0],ch[y][0],dep-1);
}
if(ch[x][1]&&ch[y][1]) {
res=min(res,find(ch[x][1],ch[y][1],dep-1));
}
if(res!=inf) return res;
if(ch[x][0]&&ch[y][1]) res=min(res,find(ch[x][0],ch[y][1],dep-1));
if(ch[x][1]&&ch[y][0]) res=min(res,find(ch[x][1],ch[y][0],dep-1));
return res+(1<<dep);
}
LL dfs(int node,int dep) {
LL res=0;
if(dep<0) return 0;
if(ch[node][0]&&ch[node][1]) {
res=dfs(ch[node][0],dep-1);
res+=dfs(ch[node][1],dep-1);
res+=find(ch[node][0],ch[node][1],dep-1)+(1<<dep);
return res;
}
if(ch[node][0]&&!ch[node][1]) return dfs(ch[node][0],dep-1);
return dfs(ch[node][1],dep-1);
}
int main () {
scanf("%d",&n);
for(int i=1;i<=n;++i) {
scanf("%d",&a[i]);
insert(i,a[i]);
}
cout<<dfs(0,30);
return 0;
}