树的重心
定义
如果以为根节点,的最大子树最小,则为树的重心。
某些定理
-
树的重心最多有两个。如果有两个,一定相邻。
-
所有点到树的重心的距离之和最小。
-
当以树的重心为根时,树的最大子树不大于 。
-
一棵树在叶子节点上加或删一条边,树的重心至多偏移一个点。
求法
求出以点 为根的子树大小 ,对于每一个点 ,维护它最大的子树大小 ,不过还有一种情况最大的子树不在以 为根的子树内,那么这样的子树对于每个 只有一个,大小为 。然后根据性质 3,如果 , 就是一个树的重心。
Link Cut Centroids
如果只有一个重心,删除已有的一条边,再加回来。
否则,两个重心一定相邻,可以把其中一个重心的子树中的所有节点都移到另一个重心上,这样就只会有一个重心了。
#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;
}