結果
問題 | No.1002 Twotone |
ユーザー |
![]() |
提出日時 | 2020-02-23 02:52:06 |
言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
結果 |
AC
|
実行時間 | 2,507 ms / 5,000 ms |
コード長 | 1,860 bytes |
コンパイル時間 | 2,574 ms |
コンパイル使用メモリ | 211,872 KB |
最終ジャッジ日時 | 2025-01-09 01:58:28 |
ジャッジサーバーID (参考情報) |
judge1 / judge2 |
(要ログイン)
ファイルパターン | 結果 |
---|---|
sample | AC * 2 |
other | AC * 33 |
ソースコード
#include<bits/stdc++.h> using namespace std; using ll = long long; vector<pair<int,int>> v[202020]; int sz[202020], used[202020]; void szdfs(int x,int p){ sz[x]=1; for(auto [to,color] : v[x]){ if(to==p||used[to])continue; szdfs(to,x); sz[x]+=sz[to]; } } int centroid(int x,int p,int total){ for(auto [to,color] : v[x]){ if(to==p||used[to])continue; if(2*sz[to]>total)return centroid(to,x,total); } return x; } map<pair<int,int>, int> MP, mp; map<int,int> ONE, one, TWO, two; int ONES, ones; ll ans; void dfs(int x,int p, int fi, int se){ if(fi && se){ ans += MP[minmax(fi,se)]++-mp[minmax(fi,se)]++; ans += ONE[fi]-one[fi]; ans += ONE[se]-one[se]; ++TWO[fi];++TWO[se]; ++two[fi];++two[se]; } else if(fi){ ans += TWO[fi]-two[fi]; ans += ONES++-ONE[fi]++; ans -= ones++-one[fi]++; } for(auto [to,color] : v[x]){ if(to==p||used[to])continue; if(!se){ if(color==fi)dfs(to, x, fi, se); else dfs(to,x,fi,color); } else if(fi==color||se==color)dfs(to, x, fi, se); } } void solve(int x){ szdfs(x,-1); if(sz[x]==1)return ; x =centroid(x,-1,sz[x]); used[x]=1; MP.clear();ONE.clear();TWO.clear(); ONES = 0; for(auto [to,color]:v[x]){ mp.clear();one.clear();two.clear(); ones = 0; if(used[to])continue; dfs(to, x, color,0); } for(auto e:MP)ans += e.second; for(auto [to,color]:v[x]){ if(used[to])continue; solve(to); } } int main(){ int n,k; cin>>n>>k; for(int i=0;i<n-1;i++){ int x,y,z; cin>>x>>y>>z; --x;--y; v[x].emplace_back(y,z); v[y].emplace_back(x,z); } solve(0); cout<<ans<<endl; return 0; }