#include using namespace std; using ll = long long; #define rep(i, n) for (int i = 0; i < (n); i++) #define repr(i, n) for (int i = (n) - 1; i >= 0; i--) #define range(a) a.begin(), a.end() int main() { int N, K; cin >> N >> K; vector>> G(N); rep(i, N - 1) { int u, v, c; cin >> u >> v >> c; u--; v--; G[u].emplace_back(v, c); G[v].emplace_back(u, c); } vector used(N); vector sz(N); auto dfs2 = [&](auto dfs2, int u, int p) -> void { sz[u] = 1; for (auto e : G[u]) if (e.first != p && not used[e.first]) { dfs2(dfs2, e.first, u); sz[u] += sz[e.first]; } }; auto dfs3 = [&](auto dfs3, int u, int p, int n) -> int { for (auto e : G[u]) if (e.first != p && not used[e.first]) { int v = e.first; if (sz[v] > n / 2) return dfs3(dfs3, v, u, n); } return u; }; auto dfs4 = [&](auto dfs4, int u, int p, int now1, int now2, map, ll> &res) -> void { res[minmax(now1, now2)]++; for (auto e : G[u]) if (e.first != p && not used[e.first]) { int v = e.first; int next1 = now1; int next2 = now2; if (next1 == -1) { next1 = e.second; } else if (next1 == e.second) { } else if (next2 == -1) { next2 = e.second; } else if (next2 == e.second) { } else { continue; } dfs4(dfs4, v, u, next1, next2, res); } }; ll ans = 0; auto dfs = [&](auto dfs, int u) -> void { dfs2(dfs2, u, -1); u = dfs3(dfs3, u, -1, sz[u]); map, ll> mp; map two; map one; ll single = 0; used[u] = true; for (auto e : G[u]) if (not used[e.first]) { int v = e.first; map, ll> np; dfs4(dfs4, v, u, e.second, -1, np); for (auto kv : np) { if (kv.first.first != -1) { // nisyoku ans += kv.second; if (mp.count(kv.first)) { ans += kv.second * mp[kv.first]; } if (one.count(kv.first.first)) { ans += kv.second * one[kv.first.first]; } if (one.count(kv.first.second)) { ans += kv.second * one[kv.first.second]; } } else if (kv.first.second != -1) { // issyoku ans += single * kv.second; if (mp.count(kv.first)) { ans -= mp[kv.first] * kv.second; } if (two.count(kv.first.second)) { ans += kv.second * two[kv.first.second]; } } } for (auto kv : np) { mp[kv.first] += kv.second; if (kv.first.first != -1) { two[kv.first.first] += kv.second; two[kv.first.second] += kv.second; } if (kv.first.first == -1 && kv.first.second != -1) { single += kv.second; one[kv.first.second] += kv.second; } } } for (auto e : G[u]) if (not used[e.first]) { dfs(dfs, e.first); } }; dfs(dfs, 0); cout << ans << endl; }