1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
| #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int N = 20001, M = 2 * N; int t, n, u, v, h[N], e[M], ne[M], idx; bool visited[N]; int ans, node; void add(int u, int v) { e[idx] = v, ne[idx] = h[u], h[u] = idx++; } int dfs(int u) { visited[u] = true; int res = 0, sum = 1; for (int i = h[u]; ~i; i = ne[i]) { int v = e[i]; if (visited[v]) continue; int s = dfs(v); res = max(res, s); sum += s; } res = max(res, n - sum); if (res < ans) { ans = res; node = u; } return sum; } int main() { scanf("%d", &t); while (t--) { scanf("%d", &n); idx = 0, ans = n; memset(h, -1, (n + 1) * 4); memset(visited, false, n + 1); for (int i = 1; i < n; ++i) { scanf("%d%d", &u, &v); add(u, v), add(v, u); } dfs(1); printf("%d %d\n", node, ans); } return 0; }
|