poj1655 (center of gravity of the tree)

Source: Internet
Author: User

Test instructions: To seek the center of gravity of a tree; center of gravity definition: The maximum number of subtree nodes with this node as root is minimal.


Solution: DFS


Code:

/******************************************************* @author: xiefubao************************************** /#pragma COMMENT (linker, "/stack:102400000,102400000") #include <iostream> #include < cstring> #include <cstdlib> #include <cstdio> #include <queue> #include <vector> #include <algorithm> #include <cmath> #include <map> #include <set> #include <stack> #include < String.h>//freopen ("In.txt", "R", stdin), using namespace std, #define EPS 1e-8#define Zero (_) (ABS (_) <=eps) Const D Ouble Pi=acos ( -1.0); typedef long Long ll;const int max=20010;const LL inf=0x3fffffff;vector<int> vec[max];int N;    int Num[max];int ansnum;int ans;void dfs (int t,int be) {int ma=0;    int sum=0;        for (int i=0;i<vec[t].size (); i++) {if (vec[t][i]==be) continue;        DFS (VEC[T][I],T);        Ma=max (Ma,num[vec[t][i]);    Sum+=num[vec[t][i]];    } ma=max (ma,n-sum-1);    num[t]=sum+1; if (ansnum>ma| |    (Ansnum==ma&&t<ans))        {Ansnum=ma;    ans=t;    }}int Main () {int t;    cin>>t;        while (t--) {scanf ("%d", &n);        ansnum=n+2;        memset (num,0,sizeof num);        for (int i=1; i<=n; i++) vec[i].clear ();            for (int i=0; i<n-1; i++) {int A, B;            scanf ("%d%d", &a,&b);            Vec[a].push_back (b);        Vec[b].push_back (a);        } dfs (1,0);    cout<<ans<< "" <<ansnum<<endl; } return 0;}

poj1655 (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.