ProgramAlgTrain/20240919/CSP常考算法模板/树上问题_dfs.cpp
2024-09-19 11:11:59 +08:00

55 lines
1.2 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#include <bits/stdc++.h>
using namespace std;
const int MAXN = 1e5 + 5;
//dep[u]代表u的深度
//leaf[u]代表以u为根的子树中深度最浅的那个叶子节点的深度。
int n , m , rt , leaf[MAXN] , dep[MAXN];
vector<int> graph[MAXN];
// 算出dep[u]和leaf[u]
int dfs(int u, int fa) { // 返回距离u点最近的叶子节点深度
dep[u] = dep[fa] + 1;
// u是叶子节点
if(graph[u].size()==1) {
leaf[u] = dep[u];
return leaf[u];
}
for(int v : graph[u]) {
if(v == fa) continue;
leaf[u] = min(dfs(v , u) , leaf[u]);
}
return leaf[u];
}
// 节点u能够被控制所需的farmer数量
int dfs2(int u, int fa) {
if(dep[u] - 1 >= leaf[u] - dep[u]) return 1;
int cnt = 0;
for (int v : graph[u]) {
if (v == fa) continue;
cnt += dfs2(v, u);
}
return cnt;
}
int main() {
// freopen("atlarge.in", "r", stdin);
// freopen("atlarge.out", "w", stdout);
memset(leaf , 0x3f , sizeof(leaf));
scanf("%d%d" , &n, &rt);
for(int i = 0; i < n - 1 ; i++) {
int u, v;
scanf("%d%d" , &u , &v);
graph[u].push_back(v);
graph[v].push_back(u);
}
dfs(rt , 0);
printf("%d\n" , dfs2(rt, 0));
return 0;
}