POJ 1655 Balancing Act (center of gravity of the tree)

Source: Internet
Author: User

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&GT;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)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.