您的位置:首页 > 其它

POJ 1655 Balancing Act【树形DP】POJ 1655 Balancing Act Balancing Act POJ 1655

2012-07-31 18:39 363 查看
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

思路

题意大意:若断开某结点,求出它的分结点的和的最大值,再求出断开每个节点结界点的最小值。

思路:DFS,将每个节点遍历一遍,求出它的子树结点的最大值。用一数组记录每个节点子树的最大值。

(一直都怕深搜的题,勇敢,不要怕他)

源码

#include<stdio.h>

#include<string.h>

#include<iostream>

#include<vector>

#include<algorithm>

#define INF 0xfffffff

using namespace std;

vector<int>v[20005];

int visit[20005];

int rem[20005];

int dp[20005], n;

void dfs(int tt)

{

int i, len=v[tt].size();

visit[1]=1;

for(i=0; i<len; i++)

{

if(!visit[v[tt][i]])

{

visit[v[tt][i]]=1;

dfs(v[tt][i]);

}

}

for(i=0; i<v[tt].size(); i++)

dp[tt]+=dp[v[tt][i]];

dp[tt]++;

int sum=0;

rem[tt]=0;

for(i=0; i<v[tt].size(); i++)

{

sum+=dp[v[tt][i]];

rem[tt]=max(rem[tt], dp[v[tt][i]]);

}

rem[tt]=max(rem[tt], n-sum-1);

return ;

}

int main()

{

int i, j, T, a, b;

scanf("%d", &T);

while(T--)

{

scanf("%d", &n);

for(i=0; i<=n; i++)

v[i].clear();

for(i=0; i<n-1; i++)

{

scanf("%d%d", &a, &b);

v[a].push_back(b);

v.[b]push_back(a);

}

memset(visit, 0, sizeof(visit));

memset(rem, 0, sizeof(rem));

memset(dp, 0, sizeof(dp));

dfs(1);

int big=INF, root;

for(i=1; i<=n; i++)

if(big>rem[i])

{

big=rem[i];

root=i;

}

printf("%d %d\n", root, big);

}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: