题意:
求树的重心。
做点分治前先做的一个题。
#include <cstdio>
#include <algorithm>
using namespace std;
const int maxn = 20005, inf = 0x3f3f3f3f;
int n, head[maxn], cnt, size[maxn], id, ans;
struct _edge {
int v, next;
} g[maxn << 1];
inline int iread() {
int f = 1, x = 0; char ch = getchar();
for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
return f * x;
}
inline void add(int u, int v) {
g[cnt] = (_edge) {v, head[u]};
head[u] = cnt++;
}
void dfs(int x, int f) {
size[x] = 1;
int res = -1;
for(int i = head[x]; ~i; i = g[i].next) if(g[i].v ^ f) {
dfs(g[i].v, x);
size[x] += size[g[i].v];
res = max(res, size[g[i].v]);
}
res = max(res, n - size[x]);
if(res < ans || (res == ans && id >= x)) {
ans = res;
id = x;
}
}
int main() {
int T = iread();
while(T--) {
n = iread();
for(int i = 1; i <= n; i++) head[i] = -1; cnt = 0;
for(int i = 1; i < n; i++) {
int u = iread(), v = iread();
add(u, v); add(v, u);
}
id = ans = inf;
dfs(1, 0);
printf("%d %d\n", id, ans);
}
return 0;
}