POJ1655 Balancing Act (树的重心)

Balancing Act
Time Limit: 1000MSMemory Limit: 65536K
Total Submissions: 10680Accepted: 4439

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
2 6 
1 2 
1 4 
4 5 
3 7 
3 1 

Sample Output

1 2

Source

 

因为最近想搞定树形DP,但我树的基础知识还不是很扎实,就打算先做一些树的基本题

求树的重心,可参考紫书 P281

代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstring>
#include<stdlib.h>
#include<algorithm>
using namespace std;
#define INF 1000000000
const int N = 20005;
int head[N],tot,n;
int son[N];
int ansge,ansnode;
struct Edge
{
    int to,next;
} edge[N*2];
void addedge(int u,int v)
{
    edge[tot].to = v;
    edge[tot].next = head[u];
    head[u] = tot++;
}
void init()
{
    tot = 0;
    memset(head,-1,sizeof(head));
    ansge = INF;
}
void dfs(int u,int fa)
{
    int balance = 0;//别定义为全局
    son[u] = 0;
    for(int i = head[u];i != -1;i = edge[i].next)
    {
        int v = edge[i].to;
        if(v == fa) continue;
        dfs(v,u);
        son[u] += son[v]+1;
        balance = max(balance,son[v]+1);
    }
    balance = max(balance,n-son[u]-1);
    if(balance < ansge || (balance==ansge&&u<ansnode))
    {
        ansge = balance;
        ansnode = u;
    }
}
int main()
{
    int t,u,v;
    scanf("%d",&t);
    while(t--)
    {
        init();
        scanf("%d",&n);
        for(int i=1; i<n; i++)
        {
            scanf("%d%d",&u,&v);
            addedge(u,v);
            addedge(v,u);
        }
        dfs(1,0);
        printf("%d %d\n",ansnode,ansge);
    }
    return 0;
}
View Code
posted @ 2015-07-28 14:24  Doli  阅读(92)  评论(0编辑  收藏  举报