/* # Algorithm ## Time Comlexity O(Nlog(N)) */ #include #include #include #include int main() { int n; scanf("%d", &n); std::vector> g(n); std::vector a(n - 1), b(n - 1), c(n - 1); for(int i = 0; i < n - 1; i++) { scanf("%d%d%d", &a[i], &b[i], &c[i]); a[i]--; b[i]--; g[a[i]].push_back(i); g[b[i]].push_back(i); } std::vector x(n), y(n), size(n), in(n), out(n), tour; std::vector> child(n), child_order(n); // LA std::map>> map_xor; { std::map map; auto dfs = [&](auto&& dfs, int v, int par, int xor_val) -> void { in[v] = tour.size(); tour.push_back(v); x[v] = xor_val; y[v] = map[xor_val]++; auto& vec = map_xor[xor_val]; if(vec.size() <= y[v]) vec.resize(y[v] + 2); vec[y[v]].push_back(in[v]); size[v] = 1; for(int id: g[v]) { int to = v ^ a[id] ^ b[id]; if(to == par) continue; dfs(dfs, to, v, xor_val ^ c[id]); child[v].push_back(to); child_order[v].push_back(in[to]); size[v] += size[to]; } tour.push_back(v); out[v] = tour.size(); map[xor_val]--; }; dfs(dfs, 0, -1, 0); } using i64 = long long; i64 ans = 0; { // 解説のパターン 1, 2 を数える std::map map; auto dfs = [&](auto&& dfs, int v, int par, int depth) -> void { if(y[v]) ans += map[x[v]] + size[v]; int tmp = map[x[v]]; for(int id: g[v]) { int to = a[id] ^ b[id] ^ v; if(to == par) continue; map[x[v]] = n - size[to]; dfs(dfs, to, v, depth + 1); } map[x[v]] = tmp; }; dfs(dfs, 0, -1, 0); } { // 解説のパターン 3 を数える std::map map; for(int i = 0; i < n; i++) map[x[i]] = -1; auto dfs = [&](auto&& dfs, int v, int par) -> void { if(v and map[x[v]] != par) { int root = (y[v] ? map[x[v]] : 0); auto& vec = map_xor[x[v]][y[v]]; i64 cnt = std::distance(lower_bound(begin(vec), end(vec), in[root]), lower_bound(begin(vec), end(vec), out[root])) - 1; ans += cnt * size[v]; } int tmp = map[x[v]]; for(int id: g[v]) { int to = a[id] ^ b[id] ^ v; if(to == par) continue; map[x[v]] = to; dfs(dfs, to, v); } map[x[v]] = tmp; }; dfs(dfs, 0, -1); } ans = (i64)n * (n - 1) - ans; printf("%lld\n", ans); }