#include #define all(vec) vec.begin(), vec.end() #define eb emplace_back using namespace std; using ll = long long; using P = pair; constexpr ll INF = (1LL << 30) - 1LL; constexpr ll LINF = (1LL << 60) - 1LL; constexpr ll MOD = 1e9 + 7; template void chmin(T &a, T b) { a = min(a, b); } template void chmax(T &a, T b) { a = max(a, b); } int n, k; vector> G; vector vis, sz; ll res; void szd(int i, int p) { sz[i] = 1; for (auto &e : G[i]) { if (e.first == p || vis[e.first]) { continue; } szd(e.first, i); sz[i] += sz[e.first]; } } int findc(int i, int p, int lim) { for (auto &e : G[i]) { if (e.first == p || vis[e.first]) { continue; } if (sz[e.first] >= lim) { return findc(e.first, i, lim); } } return i; } void dfs(int i, int p, int a, int b, map &mp) { if (a < b) { swap(a, b); } mp[P(a, b)]++; for (auto &e : G[i]) { if (e.first == p || vis[e.first]) { continue; } if (a == e.second || b == e.second) { dfs(e.first, i, a, b, mp); } else if (b == -1) { dfs(e.first, i, a, e.second, mp); } } } void calc(int v) { szd(v, -1); int c = findc(v, -1, sz[v] / 2); map mp; map cnt, m1; ll sum = 0; for (auto &e : G[c]) { if (vis[e.first]) { continue; } map mpn; dfs(e.first, c, e.second, -1, mpn); for (auto p : mpn) { if (p.first.second == -1) { res += (cnt[p.first.first] + sum - m1[p.first.first]) * p.second; } else { res += (mp[p.first] + m1[p.first.first] + m1[p.first.second]) * p.second; } } for (auto p : mpn) { if (p.first.second == -1) { m1[p.first.first] += p.second; sum += p.second; } else { res += p.second; cnt[p.first.first] += p.second; cnt[p.first.second] += p.second; mp[p.first] += p.second; } } } vis[c] = 1; for (auto &e : G[c]) { if (vis[e.first]) { continue; } calc(e.first); } } int main() { ios::sync_with_stdio(0); cin.tie(0); cin >> n >> k; G.resize(n); vis.resize(n); sz.resize(n); for (int i = 0; i < n - 1; i++) { int a, b, c; cin >> a >> b >> c; --a; --b; --c; G[a].eb(b, c); G[b].eb(a, c); } calc(0); cout << res << '\n'; }