| Time Limit: 1000MS | Memory Limit: 65536K | |
| Total Submissions: 10596 | Accepted: 4398 |
Description

Input
Output
Sample Input
1
7
2 6
1 2
1 4
4 5
3 7
3 1
Sample Output
1 2
Source
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
int const MAX = 20005;
int const INF = 0x3fffffff;
struct EDGE
{
int to, next;
}e[MAX * 2];
int head[MAX], dp[MAX];
bool vis[MAX];
int n, cnt, num, ans, b;
void Add(int u, int v)
{
e[cnt].to = v;
e[cnt].next = head[u];
head[u] = cnt ++;
}
void Init()
{
cnt = 0;
n = 0;
num = INF;
ans = n;
memset(head, -1, sizeof(head));
memset(dp, 0, sizeof(dp));
memset(vis, false, sizeof(vis));
}
void DFS(int rt)
{
vis[rt] = true;
dp[rt] = 0;
int b = 0;
for(int i = head[rt]; i != -1; i = e[i].next)
{
int son = e[i].to;
if(!vis[son])
{
DFS(son);
dp[rt] += dp[son] + 1;
b = max(b, dp[son] + 1);
}
}
b = max(b, n - dp[rt] - 1);
if(b < num || (b == num && rt < ans))
{
num = b;
ans = rt;
}
return;
}
int main()
{
int T;
scanf("%d", &T);
while(T--)
{
Init();
int st;
scanf("%d", &n);
for(int i = 0; i < n - 1; i++)
{
int u, v;
scanf("%d %d", &u, &v);
Add(v, u);
Add(u, v);
st = u;
}
DFS(st);
printf("%d %d\n", ans, num);
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
POJ 1655 Balancing Act (树形dp 树的重心)
原文地址:http://blog.csdn.net/tc_to_top/article/details/47001925