建树dfs
View Code
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
#define maxn 20005
struct Edge
{
int v, next;
} edge[maxn * 2];
int n, ecount;
int head[maxn];
int f[maxn];
int ans, ansi;
bool vis[maxn];
void addedge(int a, int b)
{
edge[ecount].v = b;
edge[ecount].next = head[a];
head[a] = ecount;
ecount++;
}
void input()
{
memset(head, -1, sizeof(head));
ecount = 0;
scanf("%d", &n);
for (int i = 0; i < n - 1; i++)
{
int a, b;
scanf("%d%d", &a, &b);
a--;
b--;
addedge(a, b);
addedge(b, a);
}
}
void dfs(int a)
{
f[a] = 1;
vis[a] = true;
int x = 0;
for (int i = head[a]; i != -1; i = edge[i].next)
if (!vis[edge[i].v])
{
dfs(edge[i].v);
f[a] += f[edge[i].v];
x = max(x, f[edge[i].v]);
}
x = max(x, n - f[a]);
if (x < ans)
{
ans = x;
ansi = a;
}
}
int main()
{
// freopen("t.txt", "r", stdin);
int t;
scanf("%d", &t);
while (t--)
{
input();
ans = 0x3f3f3f3f;
memset(vis, 0, sizeof(vis));
dfs(0);
printf("%d %d\n", ansi + 1, ans);
}
return 0;
}