Description
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
题意:
给出一棵树,求树的中心(去掉该顶点后,剩余的连通分量中的最大顶点个数最小),输出中心val、中心个数、这些点的标号。
思路:
树形dp,画一个大点的图就能看出来了,去掉一个点之后,其val为max(dfs生成树上的子树点的个数,n-非以它为根节点的点的个数)。
感想:
代码:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <cmath> #include <string> #include <map> #include <stack> #include <vector> #include <set> #include <queue> #pragma comment (linker,"/STACK:102400000,102400000") #define maxn 1005 #define MAXN 16005 #define mod 1000000000 #define INF 0x3f3f3f3f #define pi acos(-1.0) #define eps 1e-6 typedef long long ll; using namespace std; int n,m,ans,cnt,tot,flag; int dp[MAXN][2],num[MAXN]; vector<int>edge[MAXN],sta; void dfs(int u,int pre) { int i,j,t=0; for(i=0; i<edge[u].size(); i++) { int v=edge[u][i]; if(v!=pre) { dfs(v,u); t+=num[v]; dp[u][0]=max(dp[u][0],num[v]); } } num[u]=t+1; dp[u][1]=max(dp[u][0],n-num[u]); tot=min(tot,dp[u][1]); } void solve() { int i,j,t; ans=0; sta.clear(); for(i=1; i<=n; i++) { if(dp[i][1]==tot) ans++,sta.push_back(i); } printf("%d %d\n",tot,ans); for(i=0; i<ans-1; i++) { printf("%d ",sta[i]); } printf("%d\n",sta[i]); } int main() { int i,j,t; scanf("%d",&n); int u,v; for(i=1; i<=n; i++) { edge[i].clear(); dp[i][0]=0; } for(i=1; i<n; i++) { scanf("%d%d",&u,&v); edge[u].push_back(v); edge[v].push_back(u); } tot=INF; dfs(1,0); solve(); return 0; } /* 12 1 2 2 3 3 4 4 5 2 6 3 7 7 8 7 9 6 10 10 11 10 12 */