树的重心

· · 算法·理论

树的重心

定义

如果在树中选择某个节点并删除,这棵树将分为若干棵子树,统计子树节点数并记录最大值。取遍树上所有节点,使此最大值取到最小的节点被称为整个树的重心。

性质

图示

应用

以 {\color{gold}P1359 会议} 为例

题意:

求出一棵树上到所有点距离最短的点,根据定义第三条,这个点即为树的重心。所以其实该题在求树的重心。

我们可以在 DFS 中计算每个子树的大小,记录「向下」的子树的最大大小,利用总点数 - 当前子树(这里的子树指有根树的子树)的大小得到「向上」的子树的大小。

#include<bits/stdc++.h>
#define sc scanf 
#define pr printf
#define ck(x) cout<<x<<endl
#define mst(x,y) memset(x,y,sizeof(x))
#define mcp(x,y) memcpy(x,y,sizeof(x))
typedef long long ll;
const int N=1e5+10;
using namespace std;
int sz[N],w[N],cen[2],n,ans,c;
bool vis[N];
vector<int> e[N];
void getcen(int u,int fa){
    sz[u]=1;
    w[u]=0;
    for(auto v:e[u]){
        if(v!=fa){
            getcen(v,u);
            sz[u]+=sz[v];
            w[u]=max(w[u],sz[v]);
        }
    }
    w[u]=max(w[u],n-sz[u]);
    if(w[u]<=n/2){
        if(cen[0]) cen[1]=u;
        else cen[0]=u;
    }
}
void dfs(int u,int d){
    if(vis[u]) return ;
    vis[u]=1;
    ans+=d;
    for(auto v:e[u]){
        if(!vis[v]) dfs(v,d+1);
    }
}
int main(){
    int i,x,y;
    sc("%d",&n);
    for(i=1;i<n;i++){
        sc("%d%d",&x,&y);
        e[x].push_back(y);
        e[y].push_back(x);
    }
    getcen(1,0);
    if(cen[1]) c=min(cen[0],cen[1]);
    else c=cen[0];
    dfs(c,0);
    pr("%d %d",c,ans);
    return 0;
}