voidadd(int x, int y){ e[x].emplace_back(y); e[y].emplace_back(x); } // 两次bfs找树的直径 intfind(int x){ queue<int> q; vector<int> dep(n + 10, -1); dep[x] = 0; fa[x] = -1; q.push(x); while (!q.empty()) { int now = q.front(); q.pop(); for (auto nxt: e[now]) { if (dep[nxt] != -1) continue; fa[nxt] = now; dep[nxt] = dep[now] + 1; q.push(nxt); } } int ans = -1, ansid = 0; for (int i = 1; i <= n; i++) { if (dep[i] > ans) { ansid = i; ans = dep[i]; } } return ansid; }
voidwork(){ cin >> n; for (int i = 1; i <= n; ++i) e[i].clear(); for (int i = 1, x, y; i < n; ++i) { cin >> x >> y; add(x, y); } int x = find(1); // begin int y = find(x); // end vector<int> a; for (int i = y; i != -1; i = fa[i]) { a.emplace_back(i); } // fa[x] = -1 int len = a.size(); vector<pair<int, int>> ans; if (len & 1) { int p = a[len >> 1]; for (int i = 0; i <= (len >> 1); ++i) { ans.emplace_back(p, i); } } else { int p1 = a[(len >> 1) - 1], p2 = a[len >> 1]; for (int i = 1; i <= (len >> 1); i += 2){ ans.emplace_back(p1, i); ans.emplace_back(p2, i); } } cout << ans.size() << '\n'; for (auto [x, y]: ans) { cout << x << ' ' << y << '\n'; } }
intmain(){ ios::sync_with_stdio(0); cin.tie(0); int T; cin >> T; while (T--) work(); return0; }