POJ 1655 Balancing Act( 树的重心 )

Balancing Act
Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 10258   Accepted: 4234

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

 

子树中节点数最大的最小。

经典树dp,dp[i] 表示以i为根的子树当中最大的。最后O(n) 取一下答案~

#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std ;
const int N = 20010 ;
int n , dp[N] , siz[N] ;
int eh[N] , et[N<<1] , nxt[N<<1] , tot ;

void init() {
    tot = 0 ;
    memset( eh , -1 , sizeof eh ) ;
}

void addedge( int u , int v ) {
    et[tot] = v ; nxt[tot] = eh[u] ; eh[u] = tot++ ;
    et[tot] = u ; nxt[tot] = eh[v] ; eh[v] = tot++ ;
}

void Dp( int u , int fa ) {
    siz[u] = 1 ; dp[u] = 0 ;
    for( int i = eh[u] ; ~i ; i = nxt[i] ) {
        int v = et[i] ;
        if( v == fa ) continue ;
        Dp( v , u ) ;
        siz[u] += siz[v] ;
        dp[u] = max( dp[u] , siz[v] ) ;
    }
}

int main () {
     int _ ; scanf("%d",&_);
    while( _-- ) {
        init();
        scanf("%d",&n);
        for( int i = 1 ; i < n ; ++i ) {
            int u , v ; scanf("%d%d",&u,&v);
            addedge( u , v ) ;
        }
        int ans1 = -1 , ans2 = n ;
        Dp( 1 , 0 ) ;
        for( int i = 1 ; i <= n ; ++i ) {
            dp[i] = max( dp[i] , n - siz[i] ) ;
            if( dp[i] < ans2 ) {
                ans1 = i ; ans2 = dp[i] ;
            }
//            cout << i << ' ' << dp[i] << endl ;
        }
        printf("%d %d\n",ans1,ans2);
    }
    return 0 ;
}
View Code

 

posted @ 2015-06-11 21:44  hl_mark  阅读(220)  评论(0编辑  收藏  举报