SGU 134. Centroid(树的重心)

9 篇文章 0 订阅

You are given an undirected connected graph, with N vertices and N-1 edges (a tree). You must find the centroid(s) of the tree. 
In order to define the centroid, some integer value will be assosciated to every vertex. Let's consider the vertex k. If we remove the vertex k from the tree (along with its adjacent edges), the remaining graph will have only N-1 vertices and may be composed of more than one connected components. Each of these components is (obviously) a tree. The value associated to vertex kis the largest number of vertices contained by some connected component in the remaining graph, after the removal of vertex k. All the vertices for which the associated value is minimum are considered centroids.

Input

The first line of the input contains the integer number N (1<=N<=16 000). The next N-1 lines will contain two integers, a and b, separated by blanks, meaning that there exists an edge between vertex a and vertex b.

Output

You should print two lines. The first line should contain the minimum value associated to the centroid(s) and the number of centroids. The second line should contain the list of vertices which are centroids, sorted in ascending order.

Sample Input

7
1 2
2 3
2 4
1 5
5 6
6 7

Sample Output

3 1
1

题意,求树的重心(可能有 多个个)。

什么是树的重心呢:把一个点还有和他连的边从树上删掉,树有可能变成多个联通块,这些联通块中点数最多的记为这个点的maxn,所有点中maxn最小的那个点就是树的重心,那个最小值记为minn。

第一行输出那个最小值minn和重心的数量,第二行输出所有重心。


思路:从上到下dfs,删除一个点,就把树分成几个部分,他的祖先是一部分,他的第一个子树,第二个子树。。。

dfs过程中求出这些值的最大值,再记录一个总体的最小值,就可以得到答案了。


#include<vector>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#define LL long long

using namespace std;

int n,minn;
vector<int> e[16010];
vector<int> ans;

int dfs(int x,int pre)
{
    int sum = 0;
    int maxn = 0;
    for(int i=0;i<e[x].size();i++)
    {
        int xx = e[x][i];
        if(xx == pre)
            continue;
        int sz = dfs(xx,x);
        sum += sz;
        maxn = max(maxn,sz);
    }
    maxn = max(maxn,n-1-sum);
    if(maxn < minn)
    {
        minn = maxn;
        ans.clear();
        ans.push_back(x);
    }
    else if(maxn == minn)
        ans.push_back(x);
    return sum + 1;
}
int main(void)
{
    int i,j;
    scanf("%d",&n);
    for(i=1;i<=n;i++)
        e[i].clear();
    for(i=0;i<n-1;i++)
    {
        int x,y;
        scanf("%d%d",&x,&y);
        e[x].push_back(y);
        e[y].push_back(x);
    }
    minn = 1e8;
    dfs(1,-1);
    sort(ans.begin(),ans.end());
    printf("%d %d\n",minn,ans.size());
    for(i=0;i<ans.size()-1;i++)
        printf("%d ",ans[i]);
    printf("%d",ans[ans.size()-1]);

    return 0;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值