您的位置:首页 > 编程语言 > Go语言

poj 3107 Godfather(树形dp)

2017-08-28 19:58 337 查看
树的重心。

#include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;

const int MAXN = 50010;
const int MAXM = 100010;
struct Edge
{
int to,next;
}edge[MAXM];
int head[MAXN];
int son[MAXN];
int MAX[MAXN];
int res,n,tot;

void init()
{
res = MAXN;
tot = 0;
memset(head,-1,sizeof(head));
memset(son,0,sizeof(son));
memset(MAX,0,sizeof(MAX));
}

void addedge(int u, int v)
{
edge[tot].to = v;
edge[tot].next = head[u];
head[u] = tot++;
}

void dfs(int u, int fa)
{
son[u] = 1;
int ans = 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];
ans = max(ans,son[v]);
}
ans = max(ans,n-son[u]);
if(ans < res)
res = ans;
MAX[u] = ans;
}

int main()
{
init();
int a,b;
scanf("%d",&n);
for(int i = 0; i < n-1; ++i)
{
scanf("%d %d",&a,&b);
addedge(a,b);
addedge(b,a);
}
dfs(1,-1);
for(int i = 1; i <= n; ++i)
{
if(MAX[i] == res)
printf("%d ",i);
}
printf("\n");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: