树的重心(默认已会定义及存储)

先给代码

#include<bits/stdc++.h>
const int N=1000010;
const int inf=0x7f7f7f7f;
using namespace std;
int f[N],size[N],n,head[N],tot;
int rt[N],sum,cnt=1;
struct Edge{int u,v,next;}G[N<<1];
inline void addedge(int u,int v){
    G[++tot].u=u;G[tot].v=v;G[tot].next=head[u];head[u]=tot;
    G[++tot].u=v;G[tot].v=u;G[tot].next=head[v];head[v]=tot;
}//存储
inline void getrt(int u,int fa){
    size[u]=1;f[u]=0;
    for(int i=head[u];i;i=G[i].next){
        int v=G[i].v;if(v==fa)continue;
        getrt(v,u);
        size[u]+=size[v];
        f[u]=max(f[u],size[v]);
    }
    f[u]=max(f[u],sum-size[u]);
    if(f[u]==f[rt[cnt]])rt[++cnt]=u;
    else if(f[u]<f[rt[cnt]])rt[cnt]=u;//保留多个重心
}//根据定义求重心
inline int read(){
    int f=1,x=0;char ch;
    do{ch=getchar();if(ch=='-')f=-1;}while(ch<'0'||ch>'9');
    do{x=x*10+ch-'0';ch=getchar();}while(ch>='0'&&ch<='9');
    return f*x;
}
int main(){
    n=read();
    for(int i=1;i<n;i++){
        int u=read(),v=read();
        addedge(u,v);
    }
    rt[cnt]=0;sum=n;f[0]=inf;getrt(1,0);
    for(int i=1;i<=cnt;i++)printf("%d\n",rt[i]);
    return 0;
}
/*
6
1 2
2 4
2 5
1 3
3 6

1

2


*/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值