POJ1655 Balancing Act (center of gravity of the tree)

Source: Internet
Author: User

Test instructions

Give you a tree, ask for the center of the tree

If there is more than one, the output ordinal is the smallest

Ideas:

The center of the tree is the smallest number of nodes in all subtrees that are rooted in it.

Tree DP is easy to solve

/************************************************author:d evil*********************************************** * */#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>#include<vector>#include<queue>#include<Set>#include<map>#include<string>#include<cmath>#include<stdlib.h>using namespaceStd;typedefLong LongLL;Const intinf=0x3f3f3f3f;Const intmod=1e9+7;Const intn=2e4+Ten;intn,sum[n],ans,p;BOOLVis[n];vector<int>Eg[n];voidDfsintu) {    intMa=0; Vis[u]=1;  for(intI=0; I<eg[u].size (); i++)    {        intv=Eg[u][i]; if(Vis[v])Continue;        DFS (v); Sum[u]+=sum[v]+1; Ma=max (ma,sum[v]+1); } ma=max (ma,n-sum[u]-1); if(ma<ans| | ma==ans&&u<p) {ans=Ma; P=u; }}intMain () {//freopen ("In.txt", "R", stdin);    intT,x,y; scanf ("%d",&t);  while(t--) {scanf ("%d",&N); Ans=inf;  for(intI=1; i<=n;i++) {eg[i].clear (); Sum[i]=0; Vis[i]=0; }         for(intI=1; i<n;i++) {scanf ("%d%d",&x,&y);            Eg[x].push_back (y);        Eg[y].push_back (x); } DFS (1); printf ("%d%d\n", P,ans); }    return 0;}

POJ1655 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.