跳到正文

算法·理论

树的重心

Luna_From_Starry约 5 分钟
原文
文章信息与版本

文章信息

收录
2026年7月31日
更新
2026年7月31日
篇幅
约 5 分钟

版本

  1. v1当前

树的重心

定义

如果以xx为根节点,xx的最大子树最小,则xx为树的重心。

某些定理

  • 树的重心最多有两个。如果有两个,一定相邻。

  • 所有点到树的重心的距离之和最小。

  • 当以树的重心为根时,树的最大子树不大于 n2\frac{n}{2}。

  • 一棵树在叶子节点上加或删一条边,树的重心至多偏移一个点。

求法

求出以点 uu 为根的子树大小 sizusiz_u,对于每一个点 uu,维护它最大的子树大小 Maxu=max⁡{sizv}Max_{u}=\max\{siz_v\},不过还有一种情况最大的子树不在以 uu 为根的子树内,那么这样的子树对于每个 uu 只有一个,大小为 n−sizun-siz_u。然后根据性质 3,如果 Maxu≤n2Max_u\leq \frac{n}{2},uu 就是一个树的重心。

如果只有一个重心,删除已有的一条边,再加回来。

否则,两个重心一定相邻,可以把其中一个重心的子树中的所有节点都移到另一个重心上,这样就只会有一个重心了。

C++
#include<iostream>
#include<vector>
#define int long long
#define Code using
#define by namespace
#define cmy std
#define AK const int
#define problem signed
#define T1 main
Code by cmy;
AK N = 100005;
AK M = 100005;
AK INF = 1e18;
//int read() {int x = 0, w = 1;char ch = 0;while (!isdigit(ch)) {  if (ch == '-') w = -1;ch = getchar();}while (isdigit(ch)) { x = x * 10 + (ch - '0');  ch = getchar();}return x * w;}
//void write(int x){if (x < 0) putchar('-'), x = -x;if (x > 9) write(x / 10);putchar(x % 10 + '0');}
int siz[N], mxs[N], ans, n, m;
vector<int> g[N], ctr;
void add_edge(int x, int y){
	g[x].push_back(y);
	g[y].push_back(x);
}
void get_ctr(int st, int fa){
	siz[st] = 1;
	for(int i = 0; i < g[st].size(); i++){
		int v = g[st][i];
		if(v == fa) continue;
		get_ctr(v, st);
		siz[st] += siz[v];
		mxs[st] = max(mxs[st], siz[v]);
	}
	mxs[st] = max(mxs[st], n - siz[st]);
}
problem T1(){
//	freopen(".in","r",stdin);
//	freopen(".out","w",stdout);
//	ios::sync_with_stdio(false);
//	cin.tie(0);
//	cout.tie(0);
	int t;
	cin >> t;
	while(t--){
//		ctr = INF;
		cin >> n, m = n - 1;
		ctr.clear();
		for(int i = 1; i <= n; i++){
			siz[i] = 0;
			mxs[i] = 0;
			g[i].clear();
		}
		for(int i = 1; i <= m; i++){
			int x, y;
			cin >> x >> y;
			add_edge(x, y); 
		}
		get_ctr(1, -1);
		for(int i = 1, max = INF; i <= n; i++){
			if(mxs[i] < max) max = mxs[i], ctr.clear(), ctr.push_back(i);
			else if(mxs[i] == max) ctr.push_back(i);
		}
		if(ctr.size() == 1){
			cout << g[ctr[0]][0] << " " << ctr[0] << "\n" << g[ctr[0]][0] << " " << ctr[0] << "\n";
		}else{
			int d = 0;
			for(int i = 0; i < g[ctr[1]].size(); i++){
				int v = g[ctr[1]][i];
				if(v == ctr[0]) continue;
				d = v;
				break;
			}
			cout << ctr[1] << " " << d << "\n" <<  ctr[0] << " " << d << "\n";
		}
//		cout << ctr << " " <<  << "\n"; 
	}
	return 0;
}
原文