[c++树]Godfather 树的重心

[c++]Godfather 树的重心

Description

给一颗n个结点的树,节点编号为1~n,问删除一个节点之后,让剩下的分支中节点数量最多的尽量少
可能有多种方案,按编号顺序输出

Input

输入文件的第一行包含n个数(2≤n≤50000)
以下n-1行各包含两个整数。两个ai,bi的意思是ai已经和bi联通了

Output

打印所有树的重心,数字必须按递增顺序打印,用空格隔开

Sample Input

6
1 2
2 3
2 5
3 4
3 6

Sample Output

2 3

思路分析

[c++树]Godfather 树的重心_第1张图片
遍历每个数
以这个数为根

[c++树]Godfather 树的重心_第2张图片
将剩下的数分为几堆
[c++树]Godfather 树的重心_第3张图片
搜索记录下最大的一堆
遍历完后找出每个数最大的一堆中最小的一个,输出

小提示

[c++树]Godfather 树的重心_第4张图片
从上遍历时,为了防止无限循环,dfs不会往上走,所以上面的一堆需要用总数-1-下面的子节点的总数 来算

void dfs(int u,int fa)
{
    temp[u]=1;
    for(int i=now[u];i;i=per[i])
    {
        int v=son[i];
        if(v==fa)
        {
            continue;
        }
        dfs(v,u);
        temp[u]+=temp[v];
        h[u]=max(temp[v],h[u]);
    }
    h[u]=max(h[u],n-temp[u]);//上面的数
}

代码实现

#include
using namespace std;
int per[100000],now[100000],son[100000],temp[50000],h[50000];
//h[i]表示删除第i个节点之后,剩下的分支中节点数量最多的数
int sum,ans=10e8,n;
void put(int a,int b)//前项星存入树
{
    per[++sum]=now[a];
    now[a]=sum;
    son[sum]=b;
}
void dfs(int u,int fa)
{
    temp[u]=1;
    for(int i=now[u];i;i=per[i])
    {
        int v=son[i];
        if(v==fa)
        {
            continue;
        }
        dfs(v,u);
        temp[u]+=temp[v];
        h[u]=max(temp[v],h[u]);
    }
    h[u]=max(h[u],n-temp[u]);
}
int main()
{
    cin>>n;
    for(int i=1;i>a>>b;
        put(a,b);
        put(b,a);
    }
    dfs(1,0);
    for(int i=1;i<=n;i++)
    {
        ans=min(h[i],ans);
    }
    bool b=0;
    for(int i=1;i<=n;i++)//输出
    {
        if(h[i]==ans)
        {
            if(b==0)
            {
                cout<
over

你可能感兴趣的:([c++树]Godfather 树的重心)