https://ac.nowcoder.com/acm/contest/5670/B
比赛的时候发现每条边就是这两个点的到根节点的异或值异或,其实就是一个完全图的最小生成树
这题过了一车人,然后我不会写GG,后面的题都没看,人没了。结果是一个以前well known 的套路
和51nod那题一样https://blog.csdn.net/liufengwei1/article/details/107601664
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxl=1e5+10;
const int inf=2e9+10;
int n,tot,cnt;
ll ans;
int a[maxl],s[maxl],t[maxl];
int tr[maxl*30][2];
struct ed{int to,l;};
vector<ed> e[maxl];
inline void dfs(int u,int fa,int x)
{
a[u]=x;int v;
for(ed ee:e[u])
{
v=ee.to;
if(v==fa)
continue;
dfs(v,u,x^ee.l);
}
}
inline void prework()
{
scanf("%d",&n);
int u,v,w;
for(int i=1;i<=n-1;i++)
{
scanf("%d%d%d",&u,&v,&w);
++u;++v;
e[u].push_back(ed{v,w});
e[v].push_back(ed{u,w});
}
dfs(1,0,0);
}
inline void init()
{
for(int i=0;i<=tot;i++)
tr[i][0]=tr[i][1]=0;
tot=0;
}
inline void insert(int x)
{
int u=0,c;
for(int i=30;i>=0;i--)
{
c=(x>>i)&1;
if(!tr[u][c])
tr[u][c]=++tot;
u=tr[u][c];
}
}
inline int find(int x)
{
int u=0,ans=0,c;
for(int i=30;i>=0;i--)
{
c=(x>>i)&1;
if(tr[u][c])
u=tr[u][c];
else
u=tr[u][c^1],ans|=(1<<i);
}
return ans;
}
inline void solv(int l,int r,int dep)
{
if(l>=r || dep<0) return;
int cnt1=0,cnt2=0;
for(int i=l;i<=r;i++)
if((a[i]>>dep)&1)
s[++cnt1]=a[i];
else
t[++cnt2]=a[i];
for(int i=1;i<=cnt1;i++)
a[l+i-1]=s[i];
for(int i=1;i<=cnt2;i++)
a[l+cnt1+i-1]=t[i];
init();int mi=inf;
for(int i=1;i<=cnt2;i++)
insert(t[i]);
for(int i=1;i<=cnt1;i++)
mi=min(find(s[i]),mi);
if(mi<inf)
ans+=mi;
solv(l,l+cnt1-1,dep-1);solv(l+cnt1,r,dep-1);
}
inline void mainwork()
{
ans=0;
solv(1,n,30);
}
inline void print()
{
printf("%lld",ans);
}
int main()
{
prework();
mainwork();
print();
return 0;
}