1. 程式人生 > 實用技巧 >G. Xor-MST(邊權為倆點值的異或值,求MST)

G. Xor-MST(邊權為倆點值的異或值,求MST)

題:https://codeforces.com/problemset/problem/888/G

模板題

#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define MP make_pair
typedef long long ll;
const int mod=1e9+7;
const int M=2e5+5;
const int inf=0x3f3f3f3f;
const ll INF=1e18;
int a[M],trie[M*32][2];
int pos[M*32];
vector<int
>v[M]; int tot=1; ll ans=0; void pn(){ cout<<"NO"<<'\n'; } void py(){ cout<<"YES"<<'\n'; } void add(int x,int id){ int now=1; for(int i=30;i>=0;i--){ if(!trie[now][(1&(x>>i))]) trie[now][(1&(x>>i))]=++tot; now
=trie[now][(1&(x>>i))]; } pos[now]=id; v[id].pb(x); } ll query(int x,int rt,int dep){ ll res=1<<dep; for(int i=dep-1;i>=0;i--){ int nex=trie[rt][(1&(x>>i))]; if(!nex){ nex=trie[rt][1^(1&(x>>i))]; res|=(1
<<i); } rt=nex; } return res; } void dfs(int rt,int dep){ if(!rt||!dep) return ; int lson=trie[rt][0]; int rson=trie[rt][1]; dfs(lson,dep-1); dfs(rson,dep-1); if(!lson||!rson){///沒有分支了,說明只剩一個集合了 pos[rt]=pos[lson+rson]; return ; } int rid=pos[rson],lid=pos[lson]; if(v[rid].size()>v[lid].size()){ swap(rid,lid); swap(rson,lson); } ll tmp=1<<30; int m=v[rid].size(); for(int i=0;i<m;i++){ tmp=min(tmp,query(v[rid][i],lson,dep-1)); v[lid].pb(v[rid][i]); } v[rid].clear(); ans+=tmp; pos[rt]=lid; } int main(){ int n; scanf("%d",&n); for(int i=1;i<=n;i++) scanf("%d",&a[i]); sort(a+1,a+1+n); add(a[1],1); for(int i=2;i<=n;i++){ if(a[i-1]!=a[i]) add(a[i],i); } dfs(1,31); printf("%lld\n",ans); return 0; }
View Code