[poj3107]Godfather

本文详细介绍了一种求解树的重心的算法实现,通过C++代码展示了如何构造树的邻接表,以及如何通过递归计算每个节点的子树大小,最终找到使得树直径最小的节点作为树的重心。

求树的重心

 1 #include <iostream>
 2 #include <algorithm>
 3 #include <cstdio>
 4 #include <cstring>
 5 #include <cstdlib>
 6 #include <queue>
 7 #include <string>
 8 #include <vector>
 9 using namespace std;
10 
11 const int N=100100;
12 int n,h[N],r[N],to[N],tot,root,sz[N],f[N];
13 
14 void add(int u,int v){
15     to[tot]=v;
16     r[tot]=h[u];
17     h[u]=tot++;
18 }
19 
20 void getRoot(int x,int fa){
21     sz[x]=1;
22     f[x]=0;
23     for(int i=h[x];i!=-1;i=r[i]){
24         if(to[i]!=fa){
25             getRoot(to[i],x);
26             sz[x]+=sz[to[i]];
27             f[x]=max(f[x],sz[to[i]]);
28         }
29     }
30     f[x]=max(f[x],n-sz[x]);
31     if(f[x]<f[root])root=x;
32 }
33 
34 
35 int main(){
36     memset(h,-1,sizeof(h));
37     scanf("%d",&n);
38     for(int i=1,u,v;i<n;i++){
39         scanf("%d%d",&u,&v);
40         add(u,v);
41         add(v,u);
42     }
43     f[0]=0x3f3f3f3f;
44     getRoot(1,0);
45     for(int i=1;i<=n;i++)
46         if(f[i]==f[root])
47             printf("%d ",i);
48 }
View Code

 

转载于:https://www.cnblogs.com/KingSann/articles/6349845.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值