#include using namespace std; using ll = long long; struct CentroidDecomposition { int n, r; vector> g, cd; vector ord, szs; CentroidDecomposition(vector> &gg): g(gg), n(gg.size()), cd(n), szs(n,-1) { calc(0); dfs(0,-1,n,-1); } void calc(int v) { stack s; s.emplace(v); while (s.size()) { int i = s.top(); s.pop(); if (i<0) szs[~i]=1; else { szs[i]=0; s.emplace(~i); } for(auto e:g[i<0?~i:i]) { if (!szs[e]) continue; if (i<0) szs[~i] += szs[e]; else s.emplace(e); } } } void dfs(int v, int p, int sz, int root){ if (szs[v]==0) return; begin: for(auto e:g[v]) { if (p==e or szs[e]sync_with_stdio(false); int n, k; cin >> n >> k; using pii = pair; vector> g(n); vector> edges(n); for (int i = 0; i < n - 1; i++) { int u, v, c; cin >> u >> v >> c; u--, v--, c--; g[u].push_back(v); g[v].push_back(u); edges[u].emplace_back(v, c); edges[v].emplace_back(u, c); } CentroidDecomposition cd(g); vector visited(n); ll ans = 0; for (int ce : cd.ord) { int cnt0 = 0; // *, - int cnt1 = 0; // *, * map cnt2; // x, y map cnt3; // x, * map cnt4; // x, - auto f1 = [&](auto self, int node, int parent, int c1, int c2) -> void { if (c2 == -1) { cnt0++; cnt4[c1]++; } else { cnt1++; cnt2[make_pair(min(c1, c2), max(c1, c2))]++; cnt3[c1]++; cnt3[c2]++; } for (auto [child, c] : edges[node]) { if (child == parent || visited[child]) continue; if (c1 == c) { self(self, child, node, c1, c2); } else if (c2 == c || c2 == -1) { self(self, child, node, c1, c); } } }; auto f2 = [&](auto self, int node, int parent, int c1, int c2) -> void { if (c2 == -1) { ans += cnt0 - cnt4[c1] + cnt3[c1]; } else { ans += cnt2[make_pair(min(c1, c2), max(c1, c2))] + cnt4[c1] + cnt4[c2]; } for (auto [child, c] : edges[node]) { if (child == parent || visited[child]) continue; if (c1 == c) { self(self, child, node, c1, c2); } else if (c2 == c || c2 == -1) { self(self, child, node, c1, c); } } }; for (auto [child, c] : edges[ce]) { if (visited[child]) continue; f2(f2, child, ce, c, -1); f1(f1, child, ce, c, -1); } ans += cnt1; visited[ce] = true; } cout << ans << endl; }