树的重心定义:删除掉某个结点后,以这个结点的子节点为根的最大子树大小最小。
dp的思想,dfs过程类似树链刨分,有注释。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <sstream>
#include <cstring>
#include <set>
#include <cctype>
#define IO \
ios::sync_with_stdio(false); \
// cin.tie(0); \
// cout.tie(0);
using namespace std;
typedef long long LL;
const int maxn = 2e4 + 10;
const int maxm = 1e6 + 10;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const LL mod = 11092019;
int dis[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, 1, -1, 1, 1, -1, 1, -1, -1};
struct Edge
{
int before, to, w;
} e[maxn << 1];
int n, k, root, sum, head[maxn];
int size[maxn]; // 以这个点为根的子树大小
int max_p[maxn]; // 去掉这个点后最大的子树大小
void add(int u, int v)
{
e[k].before = head[u];
e[k].to = v;
head[u] = k++;
}
void DFS(int u, int fa)
{
size[u] = 1;
max_p[u] = 0;
for (int i = head[u]; i != -1; i = e[i].before)
{
int v = e[i].to;
if (v == fa)
continue;
DFS(v, u);
size[u] += size[v];
if (size[v] > max_p[u])
max_p[u] = size[v]; // 用子树大小更新max_p
}
max_p[u] = max(max_p[u], sum - size[u]); // 自己子树和回到根节点方向
if (max_p[u] < max_p[root]) // 维护root 即max_p最小的点
root = u;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
#endif
IO;
int T, a, b, c;
cin >> T;
while (T--)
{
cin >> n;
memset(head, -1, sizeof head);
k = 0;
for (int i = 0; i < n - 1; i++)
{
cin >> a >> b;
add(a, b);
add(b, a);
}
root = 0;
sum = max_p[root] = n;
DFS(1, 0);
cout << root << " " << max_p[root] << endl;
}
return 0;
}