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

Source: Internet
Author: User

Topic Links:

Poj 1655 Balancing Act

Title Description:

Given a tree, to delete a node after the formation of the forest, the largest number of sub-tree contains a minimum number of nodes?

Problem Solving Ideas:

is to seek the center of gravity of the tree, apply template on it.

Center of gravity Definition: When a node is removed from a tree, the node in the subtree with the most nodes is the least, then the deleted node is called the center of gravity.

Center of gravity Properties: Click to Visible

1#include <cstdio>2#include <cstring>3#include <iostream>4#include <algorithm>5 using namespacestd;6 Const intMAXN =20010;7 Const intINF =0x3f3f3f3f;8 structnode9 {Ten     intto, next; One} EDGE[MAXN *2]; A intHEAD[MAXN], VIS[MAXN], SON[MAXN]; - inttot, ans, num, n; - voidInit () the { -tot =0; -num =INF; -Memset (Head,-1,sizeof(head)); +memset (Vis,0,sizeof(Vis)); -Memset (son,0,sizeof(son)); + } A voidADD (int  from,intto ) at { -Edge[tot].to =to ; -Edge[tot].next = head[ from]; -head[ from] = tot + +; - } - voidDFS (intu) in { -Vis[u] =1; to     intNu =0; +      for(intI=head[u]; i!=-1; I=edge[i].next) -     { the         intv =edge[i].to; *         if(!Vis[v]) $         {Panax Notoginseng Dfs (v); -Son[u] + = Son[v] +1;//u number of child nodes theNu = Max (Nu, son[v] +1); The maximum number of nodes in a//u subtree +         } A  the     } +Nu = Max (Nu, n-son[u]-1);//(Maximum number of nodes of the U subtree, number of nodes up to U-point) -     if(Nu<num | | num==nu && ans>u) $     { $num =Nu; -Ans =u; -     } the } - intMain ()Wuyi { the     intT; -scanf ("%d", &t); Wu      while(T--) -     { About init (); $scanf ("%d", &n); -          for(intI=1; i<n; i++) -         { -             intu, v; Ascanf ("%d%d", &u, &v); + Add (U, v); the Add (V, u); -         } $DFS (1); theprintf ("%d%d\n", ans, num); the     } the     return 0; the}

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.