现在的位置: 首页 > 综合 > 正文

POJ1655Balancing Act(树形DP)

2018年02月22日 ⁄ 综合 ⁄ 共 1818字 ⁄ 字号 评论关闭

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[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);
    }
}

抱歉!评论已关闭.