/* # Algorithm ## Time Comlexity O(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), size(n); { auto dfs = [&](auto&& dfs, int v, int par, int xor_val) -> void { x[v] = xor_val; 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]); size[v] += size[to]; } }; dfs(dfs, 0, -1, 0); } using i64 = long long; i64 ans = 0; std::vector count(n); std::unordered_map count_root; { std::unordered_map map; for(int i = 0; i < n; i++) map[i] = -1; auto dfs = [&](auto&& dfs, int v, int par) -> void { if(map[x[v]] == -1) count_root[x[v]]++; else count[map[x[v]]]++; int prev = count[v]; int tmp = map[x[v]]; map[x[v]] = v; for(int id: g[v]) { int to = a[id] ^ b[id] ^ v; if(to == par) continue; dfs(dfs, to, v); i64 diff = count[v] - prev; prev = count[v]; ans += diff * (n - size[to]); } map[x[v]] = tmp; }; dfs(dfs, 0, -1); } { std::unordered_map map; for(int i = 0; i < n; i++) map[i] = -1; auto dfs = [&](auto&& dfs, int v, int par) -> void { int root = map[x[v]]; if(root == -1) ans += (count_root[x[v]] - 1) * size[v]; else ans += count[root] * size[v]; int tmp = map[x[v]]; map[x[v]] = v; for(int id: g[v]) { int to = v ^ a[id] ^ b[id]; if(to == par) continue; dfs(dfs, to, v); } map[x[v]] = tmp; }; dfs(dfs, 0, -1); } ans = (i64)n * (n - 1) - ans; printf("%lld\n", ans); }