题解:P12849 [蓝桥杯 2025 国 A] 公路

· · 题解

直接正面计算答案。

对于每一个点,考虑到 dfn 序比它小(也就是之前 dfs 到的点)所有路径的答案,很显然把每个颜色拆出来做会更简单。

对于每一种颜色,动态维护 cnt 数组。

当 dfs 进入一个子树时,那么从这个子树出来的路径,必然会经过当前边,那么对于这个颜色而言,它的 cnt 就是之前遍历过点的个数。

当 dfs 从一个子树出来时,那么从后面的点进入这个子树必然会经过当前边,再加上之前刚进入这个子树时的 cnt(两者无影响不重叠),简单加法即可。

每次只是动态修改数组的一个位置的值,那么用一个 sum 统计 cnt 数组的和即可。

#include <bits/stdc++.h> 
#define fp( i , x , y ) for( int i=(x); i<=(y); ++i ) 
#define fq( i , x , y ) for( int i=(y); i>=(x); --i ) 
#define ll long long 
using namespace std ; 
const int N = 5e5+10 ; 
int cnt[N] , n , tot , sz[N] ;
ll ans , sum ; 
vector <int> v[N] , e[N] ; 
void add( int x , int y , int z ) { 
  v[x].push_back(y) ; e[x].push_back(z) ; 
} 
void dfs( int x , int fa ) { 
  int y , z ; 
  sz[x] = 1 ; tot ++ ; 
  ans += sum ; 
  fp( i , 1 , v[x].size() ) { 
    y = v[x][i-1] ; z = e[x][i-1] ; 
    if( y == fa ) continue ; 
    int tp = cnt[z] ; 
    sum -= cnt[z] ; cnt[z] = tot ; sum += cnt[z] ; 
    dfs( y , x ) ; 
    sz[x] += sz[y] ; 
    sum -= cnt[z] ; cnt[z] = tp + sz[y] ; sum += cnt[z] ; 
  } 
}  
signed main() { 
  ios::sync_with_stdio(false) ; 
  cin.tie(0) ; 
  cin >> n ; 
  int x , y , z ; 
  fp( i , 1 , n-1 ) { 
    cin >> x >> y >> z ; 
    add( x , y , z ) ; 
    add( y , x , z ) ; 
  } 
  dfs( 1 , 0 ) ; 
  cout << 2 * ans << '\n' ; 
} 

虽然是蓝题,但是 cf 上就 2000 分,一个 dfs 就做完了,神奇吧。