Title Address: POJ 1655
The center of gravity of the tree is defined as: to find a point where the largest number of sub-tree nodes in all its subtrees is the least, then this point is the center of gravity of the tree, after the deletion of the center of gravity, the resulting tree as much as possible balance.
The center of gravity of the tree can be quickly found by using a tree-shaped DP.
The code is as follows:
#include <iostream>#include <string.h>#include <math.h>#include <queue>#include <algorithm>#include <stdlib.h>#include <map>#include <set>#include <stdio.h>#include <time.h>using namespace STD;#define LL __int64#define PI ACOs ( -1.0)//#pragma comment (linker, "/stack:1024000000")#define Root 1, N, 1#define Lson L, Mid, rt<<1#define Rson mid+1, R, Rt<<1|1Const intMod=1e9+7;Const intinf=0x3f3f3f3f;Const Doubleeqs=1e-9;Const intmaxn=20000+Ten;structnode{intV, Next;} edge[maxn<<1];intHEAD[MAXN], cnt, ans, min1, N;intSUM[MAXN];voidAddintUintV) {edge[cnt].v=v; Edge[cnt].next=head[u]; head[u]=cnt++;}voidInit () {memset(head,-1,sizeof(head)); Cnt=0; Min1=inf;}voidDfsintUintFA) {intmax1=0, I, tot=0; sum[u]=1; for(i=head[u];i!=-1; i=edge[i].next) {intV=EDGE[I].V;if(V==FA)Continue; DFS (V,U); SUM[U]+=SUM[V]; Max1=max (Max1,sum[v]); TOT+=SUM[V]; } Max1=max (max1,n-tot-1);if(MIN1>MAX1) {min1=max1; Ans=u; }}intMain () {intT, u, V, I;scanf("%d", &t); while(t--) {scanf("%d", &n); Init (); for(i=1; i<n;i++) {scanf("%d%d", &u,&v); Add (U,V); Add (V,u); } DFS (1,-1);printf("%d%d\n", ans,min1); }return 0;}
POJ 1655 Balancing Act (center of gravity of the tree)