码迷,mamicode.com
首页 > 其他好文 > 详细

SGU 134.Centroid( 树形dp )

时间:2015-12-14 23:10:26      阅读:216      评论:0      收藏:0      [点我收藏+]

标签:

一道入门树dp, 求一棵树的重心...我是有多无聊去写这种题...傻X题写了也没啥卵用以后还是少写好..

----------------------------------------------------------------

#include<cstdio>
#include<cstring>
#include<algorithm>
 
using namespace std;
 
const int maxn = 16009;
 
int sz[maxn], N;
int ans[maxn], n, ansV;
 
struct edge {
int to;
edge* next;
} E[maxn << 1], *pt = E, *head[maxn];
 
void AddEdge(int u, int v) {
pt->to = v; pt->next = head[u]; head[u] = pt++;
}
 
void Init() {
scanf("%d", &N);
for(int i = 1; i < N; i++) {
int u, v; scanf("%d%d", &u, &v); u--; v--;
AddEdge(u, v);
AddEdge(v, u);
}
n = 0;
ansV = maxn;
}
 
void dfs(int x, int fa = -1) {
sz[x] = 1;
int mx = 0;
for(edge* e = head[x]; e; e = e->next) if(e->to != fa) {
dfs(e->to, x);
mx = max(mx, sz[e->to]);
sz[x] += sz[e->to];
}
mx = max(mx, N - sz[x]);
if(mx < ansV)
ansV = mx, ans[0] = x, n = 1;
else if(mx == ansV)
ans[n++] = x;
}
 
int main() {
Init();
dfs(0);
printf("%d %d\n", ansV, n);
sort(ans, ans + n);
for(int i = 0; i < n; i++)
printf("%d ", ++ans[i]);
return 0;
}

----------------------------------------------------------------

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

Author: Mugurel Ionut Andreica
Resource: SSU::Online Contester Fall Contest #2
Date: Fall 2002
pasting

 

SGU 134.Centroid( 树形dp )

标签:

原文地址:http://www.cnblogs.com/JSZX11556/p/5046556.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!