You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

83 lines
2.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10, M = N << 1;
#define int long long
#define endl "\n"
// 链式前向星
int e[M], h[N], idx, w[M], ne[M];
void add(int a, int b, int c = 0) {
e[idx] = b, ne[idx] = h[a], w[idx] = c, h[a] = idx++;
}
vector<int> g[N]; // 邻接表,存图
int sz[N]; // sz[i]:以i为根的子树中节点个数
int son[N]; // son[i]:去掉节点i后剩下的连通分量中最大子树节点个数
int r1, r2, n;
void dfs(int u, int fa) {
sz[u] = 1; // u为根的子树中最起码有一个节点u
son[u] = 0; // 把节点u去掉后剩下的连通分量中最大子树节点个数现在还不知道预求最大先设最小
// for (int i = 0; i < g[u].size(); i++) { // 枚举u的每一条出边
for (int i = h[u]; ~i; i = ne[i]) {
// int v = g[u][i];
int v = e[i];
if (v == fa) continue;
dfs(v, u);
sz[u] += sz[v];
son[u] = max(son[u], sz[v]);
}
son[u] = max(son[u], n - sz[u]);
if ((son[u] << 1) <= n) r2 = r1, r1 = u;
}
/*
1 2
1 2
1 3
2 3
*/
signed main() {
#ifndef ONLINE_JUDGE
freopen("CF1406C.in", "r", stdin);
#endif
int T;
cin >> T;
while (T--) {
cin >> n;
// 多组测试数据,清空
memset(sz, 0, sizeof sz);
memset(son, 0, sizeof son);
// 初始化链式前向星
memset(h, -1, sizeof h);
idx = 0;
r1 = r2 = 0;
for (int i = 0; i <= n + 10; i++) g[i].clear();
for (int i = 1; i < n; i++) { // n-1条边
int x, y;
cin >> x >> y;
g[x].push_back(y);
g[y].push_back(x);
add(x, y), add(y, x);
}
dfs(1, 0); // 以1号点为入口它的父节点是0
if (!r2) {
int r3 = g[r1][0];
cout << r1 << " " << r3 << endl;
cout << r1 << " " << r3 << endl;
} else {
int r3 = r1;
for (int i = 0; i < g[r2].size(); i++) {
r3 = g[r2][i];
if (r3 != r1) break;
}
cout << r3 << " " << r2 << endl;
cout << r3 << " " << r1 << endl;
}
}
return 0;
}