SGU 134 树的重心

题目链接:http://acm.sgu.ru/problem.php?contest=0&problem=134

134. Centroid

time limit per test: 0.5 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
 

树的重心是节点

引用gx巨巨题意:

给出点的个数和几条边,求出树的重心centre及与重心相连的那个连通块中最多顶点的个数V,输出数据分为两行,一是V ,centre,第二行是重心的数目centre_num;

 

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
using namespace std;
inline int Max(int a,int b){return a>b?a:b;}
inline int Min(int a,int b){return a<b?a:b;}

#define N 20010
struct Edge{
	int from, to, nex;
}edge[N<<1];
int head[N], edgenum;
void addedge(int u, int v){
	Edge E = {u, v, head[u]};
	edge[ edgenum ] = E;
	head[u] = edgenum++;
}
int num[N], dp[N], n;
void dfs(int u, int fa){
	num[u] = 1; dp[u] = 0;
	for(int i = head[u]; ~i; i = edge[i].nex){
		int v = edge[i].to;
		if(v == fa)continue;
		dfs(v, u);
		num[u] += num[v];
		dp[u] = Max(dp[u], num[v]);
	}
	dp[u] = Max(dp[u], n - num[u]);
}

int main(){
	int i;
	scanf("%d",&n);
	memset(head, -1, sizeof(head)); edgenum = 0;
	for(i = 1; i < n; i++)
	{
		int u, v;scanf("%d %d",&u,&v);
		addedge(u, v);
		addedge(v, u);
	}
	dfs(1, -1);
	int minnum = N, pos, hehe = 0;
	for(i = 1; i <= n; i++)
		if(minnum > dp[i])
		{
			minnum = dp[i];
			pos = i;
			hehe = 1;
		}
		else if(minnum == dp[i])hehe++;

		printf("%d %d\n", minnum, hehe);
		for(i = 1; i <= n; i++)
			if(dp[i] == minnum)
				printf("%d ",i);
		return 0;
}


 

你可能感兴趣的:(SGU 134 树的重心)