题解:P12849 [蓝桥杯 2025 国 A] 公路【数据强度待检验】
每种通行证视为一种颜色,所求的答案就是树上所有路径的颜色数之和。
对每一种颜色分开考虑,发现断掉某种颜色的边会使树分为若干个连通块,直接正面计算答案是不容易的,可以反过来考虑。对于当前的颜色,总路径数就是
考虑在 dfs 过程中动态维护每种颜色的连通块大小。
具体而言,访问到某种颜色的边时,先临时存储当前的连通块大小,然后将连通块大小更新为该子树大小,递归下去处理。
回溯时,将子树中连通块的贡献计入答案,并将子树大小更新为最初临时存储的连通块大小减去子树大小。
#include<bits/stdc++.h>
#define rep(i, l, r) for(int i = (l); i <= (r); i++)
#define req(i, r, l) for(int i = (r); i >= (l); i--)
#define testcase int T; cin >> T; while(T--) solve();
#define ll long long
#define ull unsigned long long
#define pii pair<int, int>
#define vi vector<int>
#define vii vector<pii>
#define fi first
#define se second
#define all(x) begin(x), end(x)
using namespace std;
constexpr int N = 5e5 + 10, inf = 0x3f3f3f3f, INF = 0x7f7f7f7f, mod = 998244353;
constexpr double eps = 1e-9;
template<typename T> void chkmin(T& x, T y) {if(x > y) x = y;}
template<typename T> void chkmax(T& x, T y) {if(x < y) x = y;}
int n, siz[N], block[N], cnt;
ll ans;
struct edge {int ed, v;};
vector<edge> e[N];
void dfs1(int x, int fa) {
siz[x] = 1;
for(auto [ed, v] : e[x]) if(ed != fa) dfs1(ed, x), siz[x] += siz[ed];
}
void dfs2(int x, int fa) {
for(auto [ed, v] : e[x]) {
if(ed == fa) continue;
int now = block[v];
block[v] = siz[ed];
dfs2(ed, x);
ans += (ll)block[v] * (block[v] - 1);
block[v] = now - siz[ed];
}
}
signed main() {
ios :: sync_with_stdio(0); cin.tie(0); cout.tie(0);
cin >> n;
rep(i, 2, n) {
int u, v, w; cin >> u >> v >> w;
e[u].push_back({v, w});
e[v].push_back({u, w});
if(!block[w]) block[w] = n, cnt++;
}
dfs1(1, 0); dfs2(1, 0);
rep(i, 1, n) if(block[i]) ans += (ll)block[i] * (block[i] - 1);
cerr << ans << "\n";
cout << (ll)cnt * n * (n - 1) - ans << "\n";
return 0;
}