Test instructions: The number of the center of gravity of the tree and the maximum number of tree nodes after the center of gravity has been deleted size, if size is the same, select the smallest.
Idea: Randomly choose a point to convert the root map to a root map, DFS can be DP out of the answer
1348k125msc++1127b#include<cstdio> #include <iostream> #include <cstring> #include <algorithm > #include <vector>using namespace std;int n;const int n= 20020;struct edge{int v; Edge (int _v=0): V (_v) {};}; Vector<edge>es[n];int sumson[n];int ans,cur;void dfs (int u,int pa) {int tmp=-1; for (int i=0;i<es[u].size (); i++) {int v=es[u][i].v; if (V==PA) continue; DFS (V,U); sumson[u]+= (sumson[v]+1); Tmp=max (tmp,sumson[v]+1); } tmp=max (tmp,n-sumson[u]-1); if (tmp<ans| | (Tmp==ans&&u<cur)) {ans=tmp; Cur=u; }}void Ini () {for (int i=1;i<=n;i++) es[i].clear (); memset (sumson,0,sizeof (Sumson)); ans=0x3f3f3f3f;} int main () {int T; scanf ("%d", &t); while (t--) {scanf ("%d", &n); INI (); int u,v; for (int i=1;i<n;i++) {scanf ("%d%d", &u,&v); Es[u].push_back (Edge (v)); Es[v].puSh_back (Edge (U)); } dfs (1,0); printf ("%d%d\n", Cur,ans); } return 0;}
POJ 1655 balancing Act (centroid of tree-tree DP)