The center of the tree

Source: Internet
Author: User

For a root tree with n nodes, find a point as the root, which minimizes the number of nodes in the maximum subtree, in other words, the maximum number of connected blocks is minimized after the point is deleted.
Select a point as the root and set D (i) to indicate the number of nodes of the subtree with the root of I, then:

Only one DFS is required, and even memory is not required because there is no duplicate calculation.

Now here's the point:
After deleting the node I, how many nodes does the maximum connected block have?
The largest max{d (j)} nodes in the subtree of node I have n-d (i) nodes in the "upper subtree" of I!

poj1655 Balancing Act

#include <cstdio>#include <cmath>#include <cstdlib>#include <cstring>#include <iostream>#include <algorithm>#include <string>#include <sstream>#include <vector>#include <set>#include <map>#include <queue>#include <deque>#include <stack>using namespace STD;Const intmaxn=20000+Ten; vector<int>NEXT[MAXN];intD[MAXN];intSON[MAXN];intNvoidDfsintCurintFA) { for(intI=0; I<next[cur].size (); i++) {intX=next[cur][i];if(X==FA)Continue;        DFS (x,cur);        D[CUR]+=D[X]; Son[cur]=max (Son[cur],d[x]);//Record the maximum number of sub-tree nodes here} d[cur]++;}voidMaxcenter () {intans=n+1, id; for(intI=1; i<=n;i++) {intMax=max (N-d[i],son[i]);//Why is the code below wrong? is not the number of nodes to ask for maximum subtree?//for (int j=0;j<next[i].size (); j + +) {//int x=next[i][j];//if (x!=i) Max=max (max,d[x]);//        }        if(Ans>max) ans=max,id=i; }printf("%d%d\n", Id,ans);}intMain () {intT,x,y;scanf("%d", &t); while(t--) {scanf("%d", &n); for(intI=1; i<=n;i++) next[i].clear (); for(intI=1; i<=n-1; i++) {scanf("%d%d", &x,&y);            Next[x].push_back (y);        Next[y].push_back (x); }memset(d,0,sizeof(d));memset(Son,0,sizeof(son)); Dfs1,-1);    Maxcenter (); }return 0;}

The center 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.