結果
| 問題 |
No.1002 Twotone
|
| コンテスト | |
| ユーザー |
|
| 提出日時 | 2020-02-28 22:35:32 |
| 言語 | C++17 (gcc 13.3.0 + boost 1.87.0) |
| 結果 |
AC
|
| 実行時間 | 1,024 ms / 5,000 ms |
| コード長 | 3,133 bytes |
| コンパイル時間 | 2,495 ms |
| コンパイル使用メモリ | 214,288 KB |
| 最終ジャッジ日時 | 2025-01-09 02:58:11 |
|
ジャッジサーバーID (参考情報) |
judge1 / judge3 |
(要ログイン)
| ファイルパターン | 結果 |
|---|---|
| sample | AC * 2 |
| other | AC * 33 |
ソースコード
#include <bits/stdc++.h>
using namespace std;
vector<pair<int, int>> edges[200000];
bitset<200000> dead;
struct Centroid{
vector<int> centroid;
int sz[200000];
int all_sz;
int get_size(int i, int prev){
int sz = 1;
for(auto& e : edges[i]){
int j = e.first;
if(j == prev || dead[j]) continue;
sz += get_size(j, i);
}
return sz;
}
void dfs(int i, int prev){
sz[i] = 1;
bool is_centroid = true;
for(auto& e : edges[i]){
int j = e.first;
if(j == prev || dead[j]) continue;
dfs(j, i);
sz[i] += sz[j];
if(sz[j] > all_sz/2) is_centroid = false;
}
if(all_sz - sz[i] > all_sz/2) is_centroid = false;
if(is_centroid) centroid.push_back(i);
}
int calculate(int s){
centroid.clear();
all_sz = get_size(s, -1);
dfs(s, -1);
assert(centroid.size() > 0);
return centroid[0];
}
};
int64_t ans = 0;
Centroid cent;
int dfs1(int i, int p, int c){
int res = 1;
for(auto& e : edges[i]){
int j = e.first, col = e.second;
if(j == p || dead[j]) continue;
if(c == col) res += dfs1(j, i, c);
}
return res;
}
void dfs2(int i, int p, int c1, int c2, map<pair<int, int>, int>& mp){
if(c2 != -1) mp[minmax(c1, c2)]++;
for(auto& e : edges[i]){
int j = e.first, col = e.second;
if(j == p || dead[j]) continue;
if(c2 != -1 && col != c1 && col != c2) continue;
if(c1 == col){
dfs2(j, i, c1, c2, mp);
}else{
dfs2(j, i, c1, col, mp);
}
}
}
int single_V[200000], single_C[200000];
void solve(int s){
int c = cent.calculate(s);
int64_t single_sum = 0;
for(auto& e : edges[c]){
int j = e.first, col = e.second;
if(dead[j]) continue;
int res = dfs1(j, c, col);
single_V[j] = res;
single_C[col] += res;
single_sum += res;
ans += res * (single_sum - single_C[col]);
}
map<pair<int, int>, int> mp;
for(auto& e : edges[c]){
int j = e.first, col = e.second;
if(dead[j]) continue;
single_C[col] -= single_V[j];
map<pair<int, int>, int> mp2;
dfs2(j, c, col, -1, mp2);
for(auto& pp : mp2){
auto& p = pp.first;
int64_t num = 1 + single_C[p.first] + single_C[p.second];
if(mp.count(p)) num += mp[p];
ans += pp.second * num;
}
for(auto& pp : mp2) mp[pp.first] += pp.second;
single_C[col] += single_V[j];
}
for(auto& e : edges[c]){
int j = e.first, col = e.second;
single_V[j] = single_C[col] = 0;
}
dead[c] = true;
for(auto& e : edges[c]) if(!dead[e.first]) solve(e.first);
}
int main(){
int N, K;
cin >> N >> K;
for(int i=0; i<N-1; i++){
int a, b, c;
cin >> a >> b >> c;
a--; b--; c--;
edges[a].emplace_back(b, c);
edges[b].emplace_back(a, c);
}
solve(0);
cout << ans << endl;
return 0;
}