#include using namespace std; #define endl '\n' #define lfs cout<= (ll)(n); i--) using ll = long long; using ld = long double; const ll MOD = 1e9+7; //const ll MOD = 998244353; const ll INF = 1e18; using P = pair; template bool chmin(T &a,T b){if(a>b){a=b;return true;}else return false;} template bool chmax(T &a,T b){if(a void ans(bool x,T1 y,T2 z){if(x)cout< void debug(vector>&v,ll h,ll w){for(ll i=0;i&v,ll h,ll w){for(ll i=0;i void debug(vector&v,ll n){if(n!=0)cout< vector>vec(ll x, ll y, T w){ vector>v(x,vector(y,w));return v;} ll gcd(ll x,ll y){ll r;while(y!=0&&(r=x%y)!=0){x=y;y=r;}return y==0?x:y;} vectordx={1,0,-1,0,1,1,-1,-1}; vectordy={0,1,0,-1,1,-1,1,-1}; template vector make_v(size_t a,T b){return vector(a,b);} template auto make_v(size_t a,Ts... ts){ return vector(a,make_v(ts...)); } ostream &operator<<(ostream &os, pair&p){ return os << p.first << " " << p.second; } struct edge{ ll to=0,col=0; edge(){}; edge(ll t,ll c):to(t),col(c){}; }; struct CentroidDecomposition{ ll n; const vector> &g; vector used;//既に重心として選ばれたか vector sub;//部分木のサイズ CentroidDecomposition(const vector> &g):g(g){ n = g.size(); sub.assign(g.size(), 0); used.assign(g.size(), false); } ll search_centroid(ll root){ return dfs_search(root, -1, dfs_sz(root, -1) / 2 ); } ll dfs_sz(ll k, ll par){ sub[k] = 1; for(auto e:g[k]){ if(e.to == par || used[e.to])continue; sub[k] += dfs_sz(e.to, k); } return sub[k]; } ll dfs_search(ll k, ll par, ll mid){ for(auto e:g[k]){ if(e.to == par || used[e.to])continue; if(sub[e.to] > mid)return dfs_search(e.to, k, mid); } return k; } ll answer = 0; void run(){ //何か前処理を書くなら solve(0); } void solve(ll root){ ll cent = search_centroid(root); ll size = sub[root]; used[cent] = true; vector>mp; mapsum; for(auto e:g[cent]){ if(!used[e.to]){ mp.emplace_back(); dfs(e.to,-1,mp.back(),MP(e.col,-1)); for(auto z:mp.back())sum[z.fi]+=z.se; } } for(auto mp2:mp){ for(auto z:mp2){ sum[z.fi]-=z.se; } for(auto z:mp2){ if(z.fi.fi==-1)continue; if(z.fi.se==-1){ answer+=sum[MP(-1,z.fi.fi)]*z.se; answer+=sum[MP(-1,-1)]*z.se; answer-=sum[MP(z.fi.fi,-1)]*z.se; } else{ answer+=sum[z.fi]*z.se; answer+=sum[MP(z.fi.fi,-1)]*z.se; answer+=sum[MP(z.fi.se,-1)]*z.se; } } for(auto z:mp2){ sum[z.fi]+=z.se; } } for(auto e:g[cent]){ if(!used[e.to]){ solve(e.to); } } used[cent] = false; return; //統治するなら何か返す } void dfs(ll k,ll par,map&mp,P c){ mp[MP(max(c.fi,c.se),min(c.fi,c.se))]++; if(c.se!=-1){ mp[MP(-1,c.fi)]++; mp[MP(-1,c.se)]++; } else mp[MP(-1,-1)]++; for(auto e:g[k]){ if(e.to==par||used[e.to])continue; if(c.fi==e.col||c.se==e.col)dfs(e.to,k,mp,c); else if(c.se==-1)dfs(e.to,k,mp,MP(c.fi,e.col)); } } }; int main(){ cin.tie(nullptr); ios_base::sync_with_stdio(false); ll res=0,buf=0; bool judge = true; ll n,k;cin>>n>>k; vector>g(n); rep(i,0,n-1){ ll u,v,c;cin>>u>>v>>c; u--;v--;c--; g[u].EB(v,c); g[v].EB(u,c); } CentroidDecomposition cent(g); cent.run(); cout<