#include using namespace std; #include #include using namespace __gnu_pbds; int main() { cin.tie(nullptr); ios::sync_with_stdio(false); int n, k; cin >> n >> k; vector> g(n); map, int> col; for (int _ = n - 1; _--; ) { int u, v, c; cin >> u >> v >> c; --u, --v, --c; g[u].push_back(v); g[v].push_back(u); col[{u, v}] = col[{v, u}] = c; } vector be(n, true); vector sz(n), par(n); auto centroid = [&](int r) { vector vs; auto dfs = [&](auto&& self, int v, int p) -> void { vs.push_back(v); par[v] = p; sz[v] = 1; for (int u : g[v]) { if (be[u] and u != p) { self(self, u, v); sz[v] += sz[u]; } } }; dfs(dfs, r, -1); for (int v : vs) { bool ok = vs.size() - sz[v] <= vs.size() / 2; for (int u : g[v]) { if (be[u] and u != par[v]) { if (sz[u] > (int)vs.size() / 2) { ok = false; break; } } } if (ok) { return v; } } return -1; }; long long res = 0; // map mp1; gp_hash_table mp1; map, int> mp2; auto dfs = [&](auto&& self, int v, int p, set se) -> void { if (se.size() == 1) { ++mp1[*begin(se)]; } else if (se.size() == 2) { ++mp2[{*begin(se), *next(begin(se))}]; } else { assert(false); } for (int u : g[v]) { if (be[u] and u != p) { auto nse = se; nse.insert(col[{v, u}]); if (nse.size() >= 3) { continue; } self(self, u, v, nse); } } }; auto rec = [&](auto&& self, int c) -> void { c = centroid(c); // map smp1; gp_hash_table smp1; map, int> smp2; for (int v : g[c]) { if (be[v]) { mp1.clear(), mp2.clear(); dfs(dfs, v, c, {col[{c, v}]}); long long s1 = 0; for (auto e : mp1) { res += (long long)e.second * e.second; s1 += e.second; } res -= s1 * s1; for (auto e : mp2) { res += 2 * e.second; res -= 2 * (long long)(mp1[e.first.first] + mp1[e.first.second]) * e.second; res -= (long long)e.second * e.second; } for (auto e : mp1) { smp1[e.first] += e.second; } for (auto e : mp2) { smp2[e.first] += e.second; } } } long long s1 = 0; for (auto e : smp1) { res -= (long long)e.second * e.second; s1 += e.second; } res += s1 * s1; for (auto e : smp2) { res += 2 * (long long)(smp1[e.first.first] + smp1[e.first.second]) * e.second; res += (long long)e.second * e.second; } be[c] = false; for (int u : g[c]) { if (be[u]) { self(self, u); } } be[c] = true; }; rec(rec, 0); res /= 2; cout << res << '\n'; }