#include using namespace std; using ll = long long; #define rep(i, n) for (ll i = 0; i < ll(n); i++) #define rep2(i, l, r) for (ll i = ll(l); i < ll(r); i++) using vi = vector; using vvi = vector; using vll = vector; struct CentroidDecomposition { int n; vvi g; vi sz, order, dep, par; CentroidDecomposition(int n, vvi &g) : n(n), g(g) { sz.resize(n); dep.resize(n, -1); par.resize(n, -1); dfs(0, -1); calc(0, -1, 0); }; int dfs(int v, int p) { sz[v] = 1; for (auto u : g[v]) { if (u != p) sz[v] += dfs(u, v); } return sz[v]; } void calc(int v, int p, int d) { int now = v; while (true) { int nxt = -1; for (auto u : g[now]) { if (dep[u] == -1 && sz[u] * 2 > sz[now]) nxt = u; } if (nxt == -1) break; int rem = sz[now] - sz[nxt]; sz[nxt] = sz[now]; sz[now] = rem; now = nxt; } dep[now] = d; par[now] = p; for (auto u : g[now]) { if (dep[u] == -1) { calc(u, v, d + 1); } } } }; int main() { int n, k; cin >> n >> k; vvi g(n); vector>> g2(n); rep(i, n - 1) { int u, v, c; cin >> u >> v >> c; u--; v--; g[u].push_back(v); g[v].push_back(u); g2[u].push_back({v, c}); g2[v].push_back({u, c}); } CentroidDecomposition CD(n, g); ll ans = 0; rep(center, n) { map, int> cnt1; map cnt2, cnt3; ll cnt4 = 0; for (auto [v0, col0] : g2[center]) { vector> add; vector> todo = {{v0, (int)center, col0, -1}}; while (!todo.empty()) { auto [v, p, col1, col2] = todo.back(); todo.pop_back(); if (CD.dep[v] < CD.dep[center]) continue; if (col1 < col2) swap(col1, col2); if (col2 == -1) { ans += cnt2[col1]; ans += cnt4 - cnt3[col1]; } else { ans += cnt1[{col1, col2}]; ans += cnt3[col1]; ans += cnt3[col2]; ans += 1; } add.push_back({col1, col2}); for (auto [u, col] : g2[v]) { if (u != p) { if (col == col1 || col == col2) { todo.push_back({u, v, col1, col2}); } else if (col2 == -1) { todo.push_back({u, v, col1, col}); } } } } for (auto [col1, col2] : add) { if (col2 != -1) { cnt1[{col1, col2}]++; cnt2[col1]++; cnt2[col2]++; } else { cnt3[col1]++; cnt4++; } } } } cout << ans << endl; }