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)