题解:CF2231E Graph Cutting
树上启发式合并做法。
考虑枚举
设以
考虑在
AC Code
#include<bits/stdc++.h>
#define int long long
using namespace std ;
const int MAXN = 5e3 + 7 ;
vector<int> dir[MAXN] ;
int n , d ;
int sz[MAXN] , hson[MAXN] ;
void dfs1(int u , int fa) {
sz[u] = 1 ;
hson[u] = 0 ;
for (auto v : dir[u]) {
if (v == fa) continue ;
dfs1(v , u) ;
if (sz[v] > sz[hson[u]]) {
hson[u] = v ;
}
sz[u] += sz[v] ;
}
return ;
}
int t[MAXN] ;
int ans = 0 ;
void dfs3(int u , int fa , int dep) {
if (fa)
t[dep] -- ;
for (auto v : dir[u]) {
if (v == fa) continue ;
dfs3(v , u , dep + 1) ;
}
}
int e[MAXN] , lst ;
void dfs4(int u , int fa , int dep) {
e[++lst] = dep ;
for (auto v : dir[u]) {
if (v == fa) continue ;
dfs4(v , u , dep + 1) ;
}
}
void dfs2(int u , int fa , int dep) {
for (auto v : dir[u]) {
if (v == fa or v == hson[u]) {
continue ;
}
dfs2(v , u , dep + 1) ;
dfs3(v , u , dep + 1) ;
}
if (hson[u]) {
dfs2(hson[u] , u , dep + 1) ;
}
if (fa != 0) {
ans += t[d] ;
t[dep] ++ ;
}
for (auto v : dir[u]) {
if (v == fa or v == hson[u]) continue ;
lst = 0 ;
dfs4(v , u , dep + 1) ;
for (int i = 1 ; i <= lst ; i ++) {
int v = e[i] ;
int s = d + dep - v ;
if (s >= 0)
ans += t[s] ;
}
for (int i = 1 ; i <= lst ; i ++) {
int v = e[i] ;
t[v] ++ ;
}
}
return ;
}
void solve() {
cin >> n >> d ;
for (int i = 1 ; i <= n ; i ++) {
dir[i].clear() ;
}
ans = 0 ;
for (int i = 1 ; i < n ; i ++) {
int u , v ;
cin >> u >> v ;
dir[u].push_back(v) ;
dir[v].push_back(u) ;
}
for (int i = 1 ; i <= n ; i ++) {
dfs1(i , 0) ;
dfs2(i , 0 , 1) ;
dfs3(i , 0 , 1) ;
}
cout << ans / 3 << "\n" ;
}
signed main() {
ios::sync_with_stdio(0) ;
cin.tie(0) ;
cout.tie(0) ;
int t ;
cin >> t ;
while (t--) {
solve() ;
}
return 0 ;
}