树的重心
性质:
- 最大的子树最小
- 找到一个点,其所有的子树中最大的子树节点数最少,那么这个点就是这棵树的重心,删去重心后,生成的多棵树尽可能平衡
- 树中所有点到某个点的距离和中,到重心的距离和是最小的,如果有两个距离和,他们的距离和一样,则这两个点都是重心(即重心可以有两个)
- 把两棵树通过一条边相连,新的树的重心在原来两棵树重心的连线上
- 一棵树添加或者删除一个节点,树的重心最多只移动一条边的位置
- 一棵树最多有两个重心,且相邻。
思路:
- 任选节点r为根节点做dfs,dfs的同时即更新所有的d(当前子树的大小),以及最小的最大子树,注意当前子树的最大子树要考虑其父节点向上的树
- 最后得到的包含最小的最大子树的节点就是重心了
#include "bits/stdc++.h"
#define hhh printf("hhh\n")
#define see(x) (cerr<<(#x)<<'='<<(x)<<endl)
using namespace std;
typedef long long ll;
typedef pair<int,int> pr;
inline int read() {int x=0;char c=getchar();while(c<'0'||c>'9')c=getchar();while(c>='0'&&c<='9')x=x*10+c-'0',c=getchar();return x;}
const int maxn = 1e5+10;
const int inf = 0x3f3f3f3f;
const int mod = 1e9+7;
const double eps = 1e-7;
int n, heart, mx, sz[maxn];
int head[maxn], to[maxn*2], nxt[maxn*2], tot;
inline void add_edge(int u, int v) {
++tot, to[tot]=v, nxt[tot]=head[u], head[u]=tot;
++tot, to[tot]=u, nxt[tot]=head[v], head[v]=tot;
}
void dfs(int u, int fa) {
sz[u]=1; int mm=0;
for(int i=head[u]; i; i=nxt[i]) {
int v=to[i];
if(v!=fa) {
dfs(v,u);
sz[u]+=sz[v];
if(sz[v]>mm) mm=sz[v];
}
}
if(n-sz[u]>mm) mm=n-sz[u];
if(mm<mx) mx=mm, heart=u;
}
int main() {
//ios::sync_with_stdio(false); cin.tie(0);
mx=inf, n=read();
for(int i=1; i<n; ++i) add_edge(read(),read());
dfs(1,0);
printf("%d\n", heart);
}
树的直径
算法