For a root tree with n nodes, find a point as the root, which minimizes the number of nodes in the maximum subtree, in other words, the maximum number of connected blocks is minimized after the point is deleted.
Select a point as the root and set D (i) to indicate the number of nodes of the subtree with the root of I, then:
Only one DFS is required, and even memory is not required because there is no duplicate calculation.
Now here's the point:
After deleting the node I, how many nodes does the maximum connected block have?
The largest max{d (j)} nodes in the subtree of node I have n-d (i) nodes in the "upper subtree" of I!
poj1655 Balancing Act
#include <cstdio>#include <cmath>#include <cstdlib>#include <cstring>#include <iostream>#include <algorithm>#include <string>#include <sstream>#include <vector>#include <set>#include <map>#include <queue>#include <deque>#include <stack>using namespace STD;Const intmaxn=20000+Ten; vector<int>NEXT[MAXN];intD[MAXN];intSON[MAXN];intNvoidDfsintCurintFA) { for(intI=0; I<next[cur].size (); i++) {intX=next[cur][i];if(X==FA)Continue; DFS (x,cur); D[CUR]+=D[X]; Son[cur]=max (Son[cur],d[x]);//Record the maximum number of sub-tree nodes here} d[cur]++;}voidMaxcenter () {intans=n+1, id; for(intI=1; i<=n;i++) {intMax=max (N-d[i],son[i]);//Why is the code below wrong? is not the number of nodes to ask for maximum subtree?//for (int j=0;j<next[i].size (); j + +) {//int x=next[i][j];//if (x!=i) Max=max (max,d[x]);// } if(Ans>max) ans=max,id=i; }printf("%d%d\n", Id,ans);}intMain () {intT,x,y;scanf("%d", &t); while(t--) {scanf("%d", &n); for(intI=1; i<=n;i++) next[i].clear (); for(intI=1; i<=n-1; i++) {scanf("%d%d", &x,&y); Next[x].push_back (y); Next[y].push_back (x); }memset(d,0,sizeof(d));memset(Son,0,sizeof(son)); Dfs1,-1); Maxcenter (); }return 0;}
The center of the tree