#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int N = 100010, M = 2*N;
int h[N], e[M], ne[M], idx;
bool st[N];// dfs只搜索一遍
// 有向图邻接表存储
void add(int a, int b){
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
// 树和图的深度优先搜索
void dfs(int u){
st[u] = true; //表示已经搜索过当前点
// 遍历当前点的出边
for(i = h[u]; i != -1; i = ne[i]){
// i 是索引 e[i] 代表当前边
int j = e[i];
if(!j) dfs(j);
}
}
int main(){
// 初始化头部
memset(h, -1 ,sizeof h);
dfs(1); //从哪个点开始搜
return 0;
}
ACWing 846 树的重心
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
using namespace std;
const int N = 100010, M = 2*N;
int h[N], e[M], ne[M], idx;
bool st[N];// dfs只搜索一遍
int ans = N;
int n;
// 有向图邻接表存储
void add(int a, int b){
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
// 树和图的深度优先搜索
//返回从当前节点为根的子树的点的数量
int dfs(int u){
st[u] = true; //表示已经搜索过当前点
int res = 0, sum = 1;
// 遍历当前点的出边
for(int i = h[u]; i != -1; i = ne[i]){
// i 是索引 e[i] 代表当前边
int j = e[i];
if(!st[j]) {
int s = dfs(j); // 记录以当前边为根的子树的点的数量
res = max(res,s);
sum += s;
}
}
res = max(res,n-sum);
ans = min(ans,res);
return sum;
}
int main(){
// 初始化头部
memset(h, -1 ,sizeof h);
int a,b;
cin>>n;
for(int i = 0; i < n-1; i++ ){
cin>>a>>b;
add(a,b),add(b,a);
}
dfs(1); //从哪个点开始搜
cout<<ans<<'\n';
return 0;
}