树的重心 树形DP SGU 134

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 
#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;

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

void dfs(int u)
{
    tot[u] = 1;
    for(int i=0;i


你可能感兴趣的:(树形DP)