题意:给一棵树,求出树的重心,树的重心为:删除该点之后,使得形成的多棵树中节点数最大值最小。如果有多个,那么按编号大小依次输出。
思路:树形DP求重心,用个数组存储,然后排序
注意:开始用vector写的超时,,改成链式前向星AC了
#define _CRT_SECURE_NO_WARNINGS
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
#include <vector>
#include <iostream>
using namespace std;
int N;
const int maxn = 50005;
vector<int> tree[maxn]; // tree[i]表示节点i的相邻节点
int d[maxn],tot,num; // d[i]表示以i为根的子树的节点个数
#define INF 10000000
int minNode;
int minBalance,a[maxn],head[maxn],vis[maxn];
struct edge
{
int to,next;
}e[maxn<<1];
void init()
{
num=0;
memset(head,-1,sizeof(head));
memset(vis,0,sizeof(vis));
}
void addedge(int a,int b)
{
e[num].to=b;
e[num].next=head[a];
head[a]=num++;
}
void dfs(int node, int parent) // node and its parent
{
d[node] = 1; // d数组记录的是它所有的子节点数目
int maxSubTree = 0; // subtree that has the most number of nodes
// vis[]
for(int i=head[node];~i;i=e[i].next)
{
int v=e[i].to;
if(v!=parent)
{
dfs(v,node);
d[node]+=d[v];
maxSubTree=max(maxSubTree,d[v]);
}
}
/* for (int i = 0; i < tree[node].size(); i++)
{
int son = tree[node][i];
if (son != parent)
{
dfs(son, node);
d[node] += d[son];
maxSubTree = max(maxSubTree, d[son]);//这里就比较神奇了,这一步和循环外的处理可以直接把记录分支中最大的子节点数的数组省略了
}
}*/
maxSubTree = max(maxSubTree, N - d[node]); // "upside substree with (N - d[node]) nodes"
if (maxSubTree < minBalance)
{
minBalance = maxSubTree;
minNode = node;
tot=0;
a[0]=node;
}
else if(maxSubTree==minBalance)
{
a[++tot]=node;
}
}
int main()
{
while(~scanf("%d", &N))
{
init();
for (int i = 1; i <= N-1; i++)
{
int u, v;
scanf("%d%d", &u, &v);
addedge(u,v);
addedge(v,u);
}
minNode = 0;
minBalance = INF;
dfs(1, 0); // fist node as root
sort(a,a+tot+1);
for(int i=0; i<=tot; i++)
{
printf("%d%c",a[i],i==tot?'\n':' ');
}
}
return 0;
}