您的位置:首页 > 其它

树的重心 树形DP SGU 134

2015-09-03 20:14 399 查看
http://acm.sgu.ru/problem.php?contest=0&problem=134


134. Centroid

time limit per test: 0.25 sec.

memory limit per test: 4096 KB

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 k is 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


令一个点的属性值为:去除这个点以及与这个点相连的所有边后得到的连通分量的节点数的最大值。

则树的重心定义为:一个点,这个点的属性值在所有点中是最小的。

SGU 134 即要找出所有的重心,并且找出重心的属性值。

考虑用树形DP。

dp[u]表示割去u点,得到的连通分支的节点数的最大值。

tot[u]记录以u为根的这棵子树的节点数总和(包括根)。

则用一次dfs即可预处理出这两个数组。再枚举每个点,每个点的属性值其实为max(dp[u],n-tot[u]),因为有可能最大的连通分支在u的父亲及以上。然后记录答案就可以了。

代码:
#include <iostream>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;

vector<int> G[16005];
int dp[16005],tot[16005];
vector<int> ans;

void dfs(int u)
{
    tot[u] = 1;
    for(int i=0;i<G[u].size();i++)
    {
        int v = G[u][i];
        if(tot[v] == -1)
            dfs(v);
        else
            continue;
        dp[u] = max(dp[u],tot[v]);
        tot[u] += tot[v];
    }
}

int main()
{
    int n,i,j,u,v;
    scanf("%d",&n);
    for(i=0;i<=n;i++)
        G[i].clear();
    for(i=0;i<n-1;i++)
    {
        scanf("%d%d",&u,&v);
        G[u].push_back(v);
        G[v].push_back(u);
    }
    memset(dp,0,sizeof(dp));
    memset(tot,-1,sizeof(tot));
    dfs(1);
    int mini = Mod;
    for(i=1;i<=n;i++)
    {
        int tmp = max(dp[i],n-tot[i]);
        if(tmp < mini)
        {
            ans.clear();
            ans.push_back(i);
            mini = tmp;
        }
        else if(tmp == mini)
            ans.push_back(i);
    }
    printf("%d %d\n",mini,ans.size());
    sort(ans.begin(),ans.end());
    printf("%d",ans[0]);
    for(i=1;i<ans.size();i++)
        printf(" %d",ans[i]);
    puts("");
    return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: