#include #include #include #include using namespace std; long long ans = 0; pair dfs(const vector>> &G, long long v, long long p, long long c){ map C; map D; vector> Q; long long s = 1, d = 0, f = 0; for(auto e : G[v]){ if(e.first == p){ Q.emplace_back(-10,-10); continue; } auto q = dfs(G,e.first,v,e.second); Q.push_back(q); C[e.second] += q.first; D[e.second] += q.second; f += q.first; if(e.second == c) s += q.first, d += q.second; else d += q.first; ans += q.second; // diff += q.second; } long long diff = 0; for(size_t i = 0; i < G[v].size(); ++i){ if(G[v][i].first == p) continue; // assert(Q[i] >= 0); // ans += Q[i].first*(f-C[G[v][i].second]); diff += Q[i].first*(f-C[G[v][i].second]); ans += Q[i].first*(D[G[v][i].second]-Q[i].second); } assert(diff%2 == 0); ans += diff/2; return {s,d}; } int main(){ long long N, K; cin >> N >> K; vector>> G(N); for(int i = 1; i < N; ++i){ long long u, v, c; cin >> u >> v >> c; --u,--v,--c; G[u].emplace_back(v,c); G[v].emplace_back(u,c); } dfs(G,0,-1,-100); cout << ans << endl; }