AcWing 846. 树的重心
原题链接
简单
作者:
术
,
2021-01-20 16:51:07
,
所有人可见
,
阅读 262
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N=100005;
int ans=N;
int n;
int h[N],ne[N*2],e[N*2],idx;//注意*2
bool st[N];
void add(int a,int b)
{
e[idx]=b;
ne[idx]=h[a];
h[a]=idx++;
}
int dfs(int x) //以x为根节点的总节点数
{
int sum=1,res=0;
st[x]=true;//每次选择一个点u作为树的重心, 记录为st[u]=true
// cout<<1<<endl;
for(int i=h[x]; i!=-1; i=ne[i])
{
if(!st[e[i]])
{
int s=dfs(e[i]);
sum+=s;
res=max(res,s);
}
}
//st[x]=false; 不需要恢复 排列需要因为只有一个数组,而树的结点不会重复用到
//cout<<res<<endl;
res=max(res,n-sum);
ans=min(ans,res);
return sum;
}
int main()
{
cin>>n;
memset(h,-1,sizeof h);
for(int i=0;i<n-1;i++)
{
int a,b;
cin>>a>>b;
add(a,b);
add(b,a);//把树看作无向图 因为不知道ab谁为父节点
}
dfs(1);
cout<<ans;
//cout << "Hello world!" << endl;
return 0;
}