链接:C. Link Cut Centroids
树的重心定义:
在一颗树中,存在这样的一个节点,去掉这个节点之后,一颗树被分为多个连通分量,最大的连通分量的节点最少。
重心还有一些性质
1.删除重心后的所有子树,节点树都不超过原树的一半。
2.一颗树最多两个重心,而且相邻。
3.树中所有的节点到重心的距离之和最小,要是有两个重心,那么他们的距离相等。
4.这颗树要是删除或者增加一条边,重心最多只移动一条边。
这道题就是找树的重心,如果有一个重心就直接删除一条边和加上一条相同的边。如果有两个重心的话,就把其中一个重心连的一个点删去,然后加到另一个重心上。
代码:
/*
* @沉着,冷静!: 噗,这你都信!
* @LastEditors: HANGNAG
* @LastEditTime: 2020-11-18 19:54:29
* @FilePath: \ACM_vscode\DP\DP.cpp
*/
#include <algorithm>
#include <iostream>
#include <map>
#include <math.h>
#include <queue>
#include <set>
#include <stack>
#include <stdio.h>
#include <string.h>
#include <string>
#include <vector>
#define emplace_back push_back
#define pb push_back
using namespace std;
typedef long long LL;
const int mod = 1e9 + 7;
const double eps = 1e-6;
const int inf = 0x3f3f3f3f;
const int N = 2e5 + 10;
vector<int> q[N];
int n;
int root[10];
int num = 0;
int sum[N];
void dfs(int x, int f)
{
int ret = 0;
sum[x] = 1;
for (int v : q[x])
{
if (v != f)
{
dfs(v, x);
sum[x] += sum[v];
ret = max(ret, sum[v]);
}
}
ret = max(n - sum[x], ret);
if (ret < n / 2)
{
num = 0;
root[++num] = x;
}
else if (ret == n / 2)
{
root[++num] = x;
}
}
int main()
{
int t;
scanf("%d", &t);
while (t--)
{
memset(root, 0, sizeof(root));
scanf("%d", &n);
num = 0;
for (int i = 0; i <= n; i++)
{
q[i].clear();
}
int u, v;
for (int i = 1; i < n; i++)
{
scanf("%d%d", &u, &v);
q[u].pb(v);
q[v].pb(u);
}
dfs(1, -1);
if (num == 1)
{
for (int v : q[root[1]])
{
printf("%d %d\n%d %d\n", v, root[1], v, root[1]);
break;
}
}
else
{
for (int v : q[root[1]])
{
if (v != root[2])
{
printf("%d %d\n%d %d\n", v, root[1], v, root[2]); break;
}
}
}
}
return 0;
}