树的重心
寻找树的重心
#include<cstdio>
#include<cstdlib>
#include<iostream>
#define N 1000004
#define inf 0x3f3f3f3f
using namespace std;
void read(int &s){
char ch=getchar();int f=1;
for(;!isdigit(ch);ch=getchar())if(ch='-')f=-1;
for(s=0;isdigit(ch);s=s*10+ch-'0',ch=getchar());
s*=f;
}
void print(int s){
printf("%d\n",s);
return ;
}
int n;
int siz[N];
int son[N];
int root,minl;
struct Edge{
int v,nxt;
}e[N];
int head[N],tot;
void AddEdge(int u,int v){
e[++tot].v=v;
e[++tot].nxt=head[u];
head[u]=tot;
e[++tot].v=u;
e[++tot].nxt=head[v];
head[v]=tot;
}
void dfs(int node,int fa){
for(int i=head[node];i;i=e[i].nxt){
int to=e[i].v;
if(to==fa)continue;
dfs(to,node);
siz[node]+=siz[to];
son[node]=max(son[node],siz[to]);
}
son[node]=max(son[node],n-son[node]-1);
if(son[node]<minl)minl=son[node],root=node;
return ;
}
int main(){
int a,b;
minl=inf;
read(n);
for(int i=1;i<n;++i){
read(a),read(b);AddEdge(a,b);
}
dfs(1,0);
print(root);
system("pause");
return 0;
}
为什么要过别人为我安排的生活.