#include<bits/stdc++.h>
using namespace std;
const int N = 5e4 + 10 , M = 1e5 + 10;
int h[N] , e[M] , ne[M] , w[M] , idx = 0;
//sum:每个结点子树大小(包含该节点)
//r: 每个结点为根的最大子树大小
//fa:每个结点的父结点
int fa[N] , sum[N] , r[N];
int rmin = INT_MAX;
void add(int a , int b , int c)
{
w[idx] = c;
e[idx] = b;
ne[idx] = h[a];
h[a] = idx++;
}
int dfs(int x , int f)
{
sum[x] = 1;
fa[x] = f;
for(int i = h[x] ; i != -1 ; i = ne[i])
{
int j = e[i];
if(j != f)
{
sum[x] += dfs(j,x);
}
}
return sum[x];
}
int main()
{
int n;
cin >> n;
memset(h , -1 , sizeof h);
for(int i = 1 ; i <= n-1 ; i++)
{
int a , b;
cin >> a >> b;
add(a , b , 1);
add(b , a , 1);
}
dfs(1,0);
for(int i = 1 ; i <= n ; i++)
{
r[i] = n - sum[i];
for(int j = h[i] ; j != -1 ; j = ne[j])
{
int t = e[j];
if(fa[t] == i)
{
r[i] = max(r[i] , sum[t]);
}
}
rmin = min(rmin , r[i]);
}
cout << "树的重心为:";
for(int i = 1 ; i <= n ; i++)
{
if(r[i] == rmin)
{
cout << i << " ";
}
}
// for(int i = 1 ; i <= n ; i++)
// {
// cout << sum[i] << " " << fa[i] << " ";
// }
return 0;
}
树的重心(c++)
最新推荐文章于 2024-08-26 21:46:59 发布