1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| #include<bits/stdc++.h>
using namespace std;
template<typename T>void read(T&x){x=0;int fl=1;char ch=getchar();while(ch<'0'||ch>'9'){if(ch=='-') fl=-1;ch=getchar();}while(ch>='0'&&ch<='9'){x=(x<<1)+(x<<3)+ch-'0';ch=getchar();}x*=fl;} template<typename T,typename...Args>inline void read(T&t,Args&...args){read(t);read(args...);}
typedef long long LL; typedef vector<int> vi; typedef pair<int, int> pii; #define mp(x, y) make_pair(x, y) #define pb(x) emplace_back(x)
const int INF = 2e9; const int N = 100005;
int n, dis[N]; LL ans;
vector<pii> edge[N]; void dfs(int x, int f, int xorval){ dis[x] = xorval; for(auto &to : edge[x]){ if(to.first == f) continue; dfs(to.first, x, xorval ^ to.second); } }
inline int get(int val, int k){ return (val >> k) & 1; }
struct Trie{ int son[2], val; Trie(){ son[0] = son[1] = 0, val = -1; } }tr[N*20]; int tot; void insert(int val){ int now = 0; for(int i = 30; i >= 0; i--){ if(!tr[now].son[get(val, i)]) tr[now].son[get(val, i)] = ++tot; now = tr[now].son[get(val, i)]; } tr[now].val = val; } int getMin(int now, int val, int k){ if(k == -1) return tr[now].val ^ val; if(!tr[now].son[get(val, k)]) return getMin(tr[now].son[!get(val, k)], val, k-1); else return getMin(tr[now].son[get(val, k)], val, k-1); }
void dfs(int now, vi &v){ if(tr[now].val != -1){ v.pb(tr[now].val); return; } if(tr[now].son[0]) dfs(tr[now].son[0], v); if(tr[now].son[1]) dfs(tr[now].son[1], v); }
void getAns(int x, int dep){ if(tr[x].son[0]) getAns(tr[x].son[0], dep - 1); if(tr[x].son[1]) getAns(tr[x].son[1], dep - 1); if(tr[x].son[0] && tr[x].son[1]){ vi v; dfs(tr[x].son[0], v); int mn = 2e9; for(auto &val : v){ int res = getMin(tr[x].son[1], val, dep - 1); mn = min(mn, res | (1 << dep)); } ans += mn; } }
int main(){ read(n); for(int i = 1; i < n; i++){ int u, v, w; read(u, v, w); u++, v++; edge[u].pb(mp(v, w)), edge[v].pb(mp(u, w)); } dfs(1, 0, 0); for(int i = 1; i <= n; i++) insert(dis[i]); getAns(0, 30); printf("%lld\n", ans); return 0; }
|