I am a slow walker,but I never walk backwards. Abraham Lincoln

GeekZRF

POJ 1655.Balancing Act 树形dp 树的重心

Balancing Act
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 14550   Accepted: 6173

Description

Consider a tree T with N (1 <= N <= 20,000) nodes numbered 1...N. Deleting any node from the tree yields a forest: a collection of one or more trees. Define the balance of a node to be the size of the largest tree in the forest T created by deleting that node from T. 
For example, consider the tree: 

Deleting node 4 yields two trees whose member nodes are {5} and {1,2,3,6,7}. The larger of these two trees has five nodes, thus the balance of node 4 is five. Deleting node 1 yields a forest of three trees of equal size: {2,6}, {3,7}, and {4,5}. Each of these trees has two nodes, so the balance of node 1 is two. 

For each input tree, calculate the node that has the minimum balance. If multiple nodes have equal balance, output the one with the lowest number. 

Input

The first line of input contains a single integer t (1 <= t <= 20), the number of test cases. The first line of each test case contains an integer N (1 <= N <= 20,000), the number of congruence. The next N-1 lines each contains two space-separated node numbers that are the endpoints of an edge in the tree. No edge will be listed twice, and all edges will be listed.

Output

For each test case, print a line containing two integers, the number of the node with minimum balance and the balance of that node.

Sample Input

1
7
2 6
1 2
1 4
4 5
3 7
3 1

Sample Output

1 2

Source

 
题意:求一棵树的编号最小的重心
思路:树形dp。
代码:
#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<set>
#include<bitset>
#include<map>
#include<queue>
#include<stack>
#include<vector>
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
#define bug(x) cout<<"bug"<<x<<endl;
#define PI acos(-1.0)
#define eps 1e-8
const int N=1e5+100,M=1e5+100;
const int inf=0x3f3f3f3f;
const ll INF=1e18+7,mod=1e9+7;
int n;
vector<int>G[N];
int si[N],maxx[N];
int ans;
int dfs(int u,int fa)
{
    for(int i=0; i<G[u].size(); i++)
    {
        int v=G[u][i];
        if(v==fa) continue;
        si[u]+=dfs(v,u);
        maxx[u]=max(maxx[u],si[v]);
    }
    si[u]++;
    maxx[u]=max(maxx[u],n-si[u]);
    if(maxx[u]<maxx[ans]) ans=u;
    else if(maxx[u]==maxx[ans]&&u<ans) ans=u;
    return si[u];
}
int main()
{
    int T;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%d",&n);
        for(int i=1; i<n; i++)
        {
            int u,v;
            scanf("%d%d",&u,&v);
            G[u].push_back(v);
            G[v].push_back(u);
        }
        memset(si,0,sizeof(si));
        memset(maxx,0,sizeof(maxx));
        ans=0,maxx[0]=inf;
        dfs(1,0);
        printf("%d %d\n",ans,maxx[ans]);
        for(int i=0;i<=n+10;i++) G[i].clear();
    }
    return 0;
}
树形dp

 

posted on 2017-09-19 22:09  GeekZRF  阅读(151)  评论(0编辑  收藏  举报

导航