sgu 134. Centroid 树形dp

xiaoxiao2021-02-28  37

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.


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.


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


#include <bits/stdc++.h> using namespace std; const int M=16000+5; int n; int tot=2; int head[M]; int dp[M]; int m[M]; bool vis[M]; int ans=M; int num=1; struct node{ int to; int next; }edge[2*M]; void add_edge(int a,int b){ edge[tot].to=b; edge[tot].next=head[a]; head[a]=tot++; edge[tot].to=a; edge[tot].next=head[b]; head[b]=tot++; } int dfs(int x){ vis[x]=1; int now=1; for(int i=head[x];i!=0;i=edge[i].next){ if(!vis[edge[i].to]){ int mmm=dfs(edge[i].to); dp[x]=max(dp[x],mmm); now+=mmm; } } if(x!=1){ dp[x]=max(dp[x],n-now); } if(ans==dp[x]){ num++; } else{ if(dp[x]<ans){ ans=dp[x]; num=1; } } return now; } int main() { scanf("%d",&n); for(int i=1;i<n;i++){ int a,b; scanf("%d%d",&a,&b); add_edge(a,b); } dfs(1); printf("%d %d\n",ans,num); for(int i=1;i<=n;i++){ if(dp[i]==ans){ printf("%d ",i); } } return 0; }