首页 > 其他 > 详细

POJ1655Balancing Act(树形DP)

时间:2014-03-26 22:27:49      阅读:679      评论:0      收藏:0      [点我收藏+]

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: 
bubuko.com,布布扣

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[p][1]表示以p为根的子树节点个数(包括本身),dp[p][0]表示以p为balance node的最大子集个数。
#include<stdio.h>
#include<iostream>
#include<vector>
using namespace std;
vector<int>edg[20005];
int dp[20005][2],vist[20005],N;
int max(int a,int b)
{
    return a>b?a:b;
}
void dfs(int p)
{
    dp[p][0]=0;dp[p][1]=1; vist[p]=1;
    for(int i=0;i<edg[p].size();i++)
    {
        int son=edg[p][i];
        if(vist[son])continue;
        dfs(son);
         dp[p][1]+=dp[son][1];
         dp[p][0]=max(dp[p][0],dp[son][1]);
    }
    dp[p][0]=max(dp[p][0],N-dp[p][1]);//注意这个
}
int main()
{
    int t,a,b;
    scanf("%d",&t);
    while(t--)
    {
        scanf("%d",&N);
        for(int i=1;i<=N;i++)
        vist[i]=0,edg[i].clear();
        for(int i=1;i<N;i++)
        {
            scanf("%d%d",&a,&b);
            edg[a].push_back(b);
            edg[b].push_back(a);
        }
        dfs(1);
        int min=99999999,id;
        for(int i=1;i<=N;i++)
        if(min>dp[i][0])
        {
            min=dp[i][0]; id=i;
        }
        printf("%d %d\n",id,min);
    }
}


POJ1655Balancing Act(树形DP),布布扣,bubuko.com

POJ1655Balancing Act(树形DP)

原文:http://blog.csdn.net/u010372095/article/details/22199625

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!