首页 > 其他分享 >树的重心

树的重心

时间:2022-08-29 20:45:39浏览次数:69  
标签:结点 重心 int tt ff 最大值

给定一颗树,树中包含 n 个结点(编号 1∼n)和 n−1

条无向边。

请你找到树的重心,并输出将重心删除后,剩余各个连通块中点数的最大值。

重心定义:重心是指树中的一个结点,如果将这个点删除后,剩余各个连通块中点数的最大值最小,那么这个节点被称为树的重心。

输入格式

第一行包含整数 n

,表示树的结点数。

接下来 n−1

行,每行包含两个整数 a 和 b,表示点 a 和点 b

之间存在一条边。

输出格式

输出一个整数 m

,表示将重心删除后,剩余各个连通块中点数的最大值。

数据范围

1≤n≤105

 

输入样例

9
1 2
1 7
1 4
2 8
2 5
4 3
3 9
4 6

输出样例:

4
#include<bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;
int n, e[N<<1], h[N], ne[N<<1], idx, ans = N;
void add(int ff, int tt)
{
    e[idx] = tt;
    ne[idx] = h[ff];
    h[ff] = idx ++ ;
} 
bool vis[N];
int dfs(int now)
{
    vis[now] = true;
    int sum = 1, temp = 0;
    for(int i = h[now]; ~i; i = ne[i])
    {
        int tt = e[i];
        if(!vis[tt])
        {
            int t = dfs(tt);
            sum += t;
            temp = max(temp, t);
        }
    }
    temp = max(temp, n-sum);
    ans = min(temp, ans);
    return sum;
}
int main()
{
    memset(h, -1, sizeof h);
    cin >> n;
    for(int i = 0; i < n - 1; i ++ )
    {
        int ff, tt;
        cin >> ff >> tt;
        add(ff, tt);
        add(tt, ff);
    }
    dfs(1);
    printf("%d\n", ans);


    return 0;
}

 

标签:结点,重心,int,tt,ff,最大值
From: https://www.cnblogs.com/leyuo/p/16637301.html

相关文章