题意:给你一棵有n个节点的树,删除一个节点,使删除该点后所形成的森林中节点数最多的树尽可能小,可能有多种方案,按编号顺序输出。
分析:这道题是裸的树的重心题,那么我们就查找每一个节点的子树大小,不难发现
num[i]=∑num[son[i]]
n
u
m
[
i
]
=
∑
n
u
m
[
s
o
n
[
i
]
]
,然后我们需要保存每一个点删除后最大树的大小
ans[i]
a
n
s
[
i
]
,仍然不难发现
ans[i]=max(num[son[i]])
a
n
s
[
i
]
=
m
a
x
(
n
u
m
[
s
o
n
[
i
]
]
)
,最后利用一个小小的技巧,即时保存在答案数组中,具体请看代码。
详细代码如下:
#include <bits/stdc++.h>
using namespace std;
int frist[50010];
int net[100010];
int c[100010];
int num[50010];
int ans[50010];
int maxn=10000000;
int total=0,n;
bool tot[50010];
int read() {
int ans=0,flag=1;
char ch=getchar();
while( (ch>'9' || ch<'0') && ch!='-' ) ch=getchar();
if(ch=='-') flag=-1,ch=getchar();
while(ch>='0' && ch<='9') ans=ans*10+ch-'0',ch=getchar();
return ans*flag;
}
void addedge(int x,int y) {//邻接表保存
c[++total]=y;
net[total]=frist[x];
frist[x]=total;
c[++total]=x;
net[total]=frist[y];
frist[y]=total;
}
void work(int son,int fa) {
for(int i=frist[son];i;i=net[i]) {
if(c[i]!=fa) {
work(c[i],son);
num[son]+=num[c[i]];
if(num[c[i]]>ans[son]) ans[son]=num[c[i]];
}
}
ans[son]=max(ans[son],n-num[son]);//由于我们并没有加入父亲那边的树,所以我们需要比较一下
//储存答案技巧
if(ans[son]<maxn) maxn=ans[son],memset(tot,0,sizeof(tot)),tot[son]=1;
else if(ans[son]==maxn) tot[son]=1;
return ;
}
int main() {
int i;
n=read();
for(i=1;i<=n;i++) {
num[i]=1;
}
for(i=1;i<n;i++) {
addedge(read(),read());
}
work(1,0);
for(i=1;i<=n;i++) {
if(tot[i]) printf("%d ",i);
}
return 0;
}
by:Chlience