链接:http://poj.org/problem?id=3107
题意:找树的重心。。定义就是以重心为根的所有子树里面最大的最小。。。
做法:瞎dfs一下就行了。。记录一下子树。。
重点:!!!!这个题vector暴力存边并不行。。。。水了这么多水题第一次被卡了。该来的总还是会来。。所以用链式向前星来模拟邻接表。。比vector速度快的很多,也不难写。。。
代码:
#include<stdio.h>
#include<iostream>
#include<vector>
#include<cstring>
#include<algorithm>
using namespace std;
const int MAX=50005;
int vis[MAX];
int low[MAX];
int Mlow[MAX];
int n;
int R[MAX];
struct E{
int next,n,to;
}node[MAX*2];
int head[MAX];
int num=0;
void Add(int from,int to)
{
node[num].to=to;
//node[num].n=n;
node[num].next=head[from];//当前结点指向以前的头结点
head[from]=num++;//当前结点变为头结点
}
void init(){
num=0;
memset(vis,0,sizeof(vis));
memset(Mlow,0,sizeof(Mlow));
memset(head,-1,sizeof(head));
}
int dfs(int x){
int ret=1;
vis[x]=1;
int t=head[x];
while(t!=-1){
if(vis[node[t].to]==0){
ret+=dfs(node[t].to);
}
t=node[t].next;
}
low[x]=ret;
return ret;
}
void dfs2(int x){
vis[x]=1;
int ret=n-low[x];
int t=head[x];
while(t!=-1){
if(vis[node[t].to]==0){
ret=max(ret,low[node[t].to]);
}
t=node[t].next;
}
t=head[x];
while(t!=-1){
if(vis[node[t].to]==0){
dfs2(node[t].to);
}
t=node[t].next;
}
Mlow[x]=ret;
return;
}
int main(){
while(scanf("%d",&n)!=EOF){
int a,b;
init();
for(int i=0;i<n-1;i++){
scanf("%d%d",&a,&b);
Add(a,b);
Add(b,a);
}
dfs(1);
memset(vis,0,sizeof(vis));
dfs2(1);
int MI=n;
int cnt=0;
for(int i=1;i<=n;i++){
if(Mlow[i]<MI){
MI=Mlow[i];
cnt=0;
R[cnt++]=i;
}
else if(Mlow[i]==MI){
R[cnt++]=i;
}
}
sort(R,R+cnt);
for(int i=0;i<cnt;i++){
printf("%d",R[i]);
if(i!=cnt-1) printf(" ");
else printf("
");
}
}
}