传送门:【POJ】1655 Balancing Act
题目分析:树的重心模板题。
代码如下:
#include <cstdio> #include <cstring> #include <algorithm> using namespace std ; typedef long long LL ; #define travel( e , H , u ) for ( Edge* e = H[u] ; e ; e = e -> next ) #define rep( i , a , b ) for ( int i = ( a ) ; i < ( b ) ; ++ i ) #define rev( i , a , b ) for ( int i = ( a ) ; i >= ( b ) ; -- i ) #define FOR( i , a , b ) for ( int i = ( a ) ; i <= ( b ) ; ++ i ) #define clr( a , x ) memset ( a , x , sizeof a ) #define cpy( a , x ) memcpy ( a , x , sizeof a ) #define F( i ) ( ( ( i ) - 1 ) % n + 1 ) const int MAXN = 20005 ; const int MAXE = 40005 ; struct Edge { int v ; Edge* next ; } E[MAXE] , *H[MAXN] , *edge ; int siz[MAXN] ; int num[MAXN] ; int root ; int n ; void clear () { edge = E ; clr ( H , 0 ) ; } void addedge ( int u , int v ) { edge -> v = v ; edge -> next = H[u] ; H[u] = edge ++ ; } void dfs ( int u , int fa = 0 ) { siz[u] = 1 ; num[u] = 0 ; travel ( e , H , u ) { int v = e -> v ; if ( v != fa ) { dfs ( v , u ) ; siz[u] += siz[v] ; if ( siz[v] > num[u] ) num[u] = siz[v] ; } } num[u] = max ( num[u] , n - siz[u] ) ; if ( num[u] < num[root] ) root = u ; } void solve () { int x , y ; scanf ( "%d" , &n ) ; num[root = 0] = n ; clear () ; rep ( i , 1 , n ) { scanf ( "%d%d" , &x , &y ) ; addedge ( x , y ) ; addedge ( y , x ) ; } dfs ( 1 ) ; printf ( "%d %d\n" , root , num[root] ) ; } int main () { int T ; scanf ( "%d" , &T ) ; while ( T -- ) solve () ; return 0 ; }