#define _CRT_SECURE_NO_WARNINGS #pragma comment (linker, "/STACK:526000000") #include "bits/stdc++.h" using namespace std; typedef string::const_iterator State; #define eps 1e-11L #define MAX_MOD 1000000007LL #define GYAKU 500000004LL #define MOD 998244353LL #define seg_size 262144 #define pb push_back #define mp make_pair typedef long long ll; #define REP(a,b) for(long long (a) = 0;(a) < (b);++(a)) #define ALL(x) (x).begin(),(x).end() unsigned long xor128() { static unsigned long x = 123456789, y = 362436069, z = 521288629, w = time(NULL); unsigned long t = (x ^ (x << 11)); x = y; y = z; z = w; return (w = (w ^ (w >> 19)) ^ (t ^ (t >> 8))); } void init() { iostream::sync_with_stdio(false); cout << fixed << setprecision(20); } //#define int ll int union_tree[1000001]; int cnt[1000001]; vector> edges[1000001]; int dp[1000001]; int union_find(int now) { if (now == union_tree[now]) return now; return union_tree[now] = union_find(union_tree[now]); } void union_merge(int a, int b) { a = union_find(a); b = union_find(b); union_tree[a] = b; return; } void solve() { int n, k; cin >> n >> k; REP(i, n-1) { int a, b, c; cin >> a >> b >> c; a--; b--; c--; edges[c].push_back(mp(a, b)); } REP(i, n) { union_tree[i] = i; } int ans = 0; for (int q = 0; q < k; ++q) { set appeared; for (auto x : edges[q]) { union_merge(x.first, x.second); appeared.insert(x.first); appeared.insert(x.second); } for (auto x : appeared) { cnt[union_find(x)]++; } for (auto x : appeared) { int geko = cnt[union_find(x)] - 1LL; ans += dp[x] * geko; } for (auto x : appeared) { int geko = cnt[union_find(x)] - 1LL; dp[x] += geko; } for (auto x : edges[q]) { union_tree[x.first] = x.first; union_tree[x.second] = x.second; cnt[x.first] = 0; cnt[x.second] = 0; } } cout << ans << endl; } #undef int int main() { init(); solve(); }