#include #include #include using namespace std; using i32 = int32_t; using u32 = uint32_t; using i64 = int64_t; using u64 = uint64_t; #define rep(i,n) for(int i=0; i<(n); i++) class CoordinateCompress { using Elem = i64; static const Elem negInf = -1001001001001001001; vector> G; vector res; vector mRealval; Elem mMaxcoord; bool ok = true; void calc() { if (ok) return; sort(G.begin(), G.end()); res.resize(G.size()); mRealval.clear(); Elem x = negInf; int p = -1; rep(i, G.size()) { if (x != G[i].first) { x = G[i].first; mRealval.push_back(x); p++; } res[G[i].second] = p; } mMaxcoord = p; ok = true; } public: int push(Elem x) { ok = false; G.push_back({ x,(int)G.size() }); return G.back().second; } int operator[](int i) { calc(); return res[i]; } Elem realval(int x) { calc(); return mRealval[x]; } Elem maxcoord() { calc(); return mMaxcoord; } }; struct Edge{ int to; u32 h; }; int N; vector> E; vector> hldE; vector P; vector Z; CoordinateCompress CCH; vector H; vector> black_stack; vector prev_black; vector block_size; vector root_size; i64 ans; void dfs(int p = 0, int pre = -1){ if(pre == -1){ black_stack.assign(N,{0}); prev_black.assign(N,0); block_size.assign(N,0); root_size.assign(N,N); ans = 0; } int h = H[p]; block_size[p] = Z[p]; prev_black[p] = black_stack[h].back(); if(prev_black[p] != 0) block_size[prev_black[p]] -= Z[p]; else root_size[h] -= Z[p]; for(int e : hldE[p]) if(e != pre){ black_stack[H[p]].push_back(e); dfs(e,p); black_stack[H[p]].pop_back(); } } int main(){ cin >> N; E.resize(N); hldE.resize(N); rep(i,N-1){ int u,v; u32 c; cin >> u >> v >> c; u--; v--; E[u].push_back({ v,c }); E[v].push_back({ u,c }); hldE[u].push_back(v); hldE[v].push_back(u); } vector I = {0}; P.assign(N,-1); H.assign(N,0); rep(i,I.size()){ int p = I[i]; for(auto e : E[p]){ if(P[p] == e.to) continue; I.push_back(e.to); P[e.to] = p; H[e.to] = H[p] ^ e.h; } } Z.assign(N,1); for(int i=N-1; i>=1; i--) Z[P[I[i]]] += Z[I[i]]; rep(i,N) H[i] = CCH.push(H[i]); rep(i,N) H[i] = CCH[H[i]]; dfs(); i64 ans = 0; for(int p=1; p