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;
}