diff --git a/TangDou/Topic/HuanGenDp/CF1406.cpp b/TangDou/Topic/HuanGenDp/CF1406.cpp new file mode 100644 index 0000000..3604f31 --- /dev/null +++ b/TangDou/Topic/HuanGenDp/CF1406.cpp @@ -0,0 +1,62 @@ +#include +using namespace std; +const int N = 1e5 + 10; +#define int long long +#define endl "\n" + +vector 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的每一条出边 + int v = g[u][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; +} + +signed main() { + int T; + cin >> T; + while (T--) { + cin >> n; + // 多组测试数据,清空 + memset(sz, 0, sizeof sz); + memset(son, 0, sizeof son); + 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); + } + + 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; +} \ No newline at end of file diff --git a/TangDou/Topic/HuanGenDp/CF1406C.cpp b/TangDou/Topic/HuanGenDp/CF1406C.cpp deleted file mode 100644 index 4ef55ac..0000000 --- a/TangDou/Topic/HuanGenDp/CF1406C.cpp +++ /dev/null @@ -1,71 +0,0 @@ -#include -#define N 100005 -using namespace std; -int n, head[N], ver[2 * N], Next[2 * N], tot = 0; -void add(int x, int y) { - ver[++tot] = y, Next[tot] = head[x], head[x] = tot; -} -vector c; -int mx[N], sz[N]; -int mn = 0x3f3f3f3f; -void dfs(int x, int pre) { - for (int i = head[x]; i; i = Next[i]) { - int y = ver[i]; - if (y == pre) continue; - dfs(y, x); - sz[x] += (sz[y] + 1); - mx[x] = max(mx[x], sz[y] + 1); - } - mx[x] = max(mx[x], n - 1 - sz[x]); - mn = min(mn, mx[x]); -} -void solve() { - cin >> n; - tot = 0; - mn = 0x3f3f3f3f; - c.clear(); - for (int i = 0; i <= n; i++) { - head[i] = 0; - mx[i] = 0; - sz[i] = 0; - } - for (int i = 1; i < n; i++) { - int x, y; - cin >> x >> y; - add(x, y); - add(y, x); - } - dfs(1, 0); - for (int i = 1; i <= n; i++) { - if (mx[i] == mn) { - c.push_back(i); - } - } - if (c.size() == 1) { - for (int i = head[c[0]]; i; i = Next[i]) { - int y = ver[i]; - cout << c[0] << " " << y << endl; - cout << c[0] << " " << y << endl; - return; - } - } else { - int tmp; - for (int i = head[c[0]]; i; i = Next[i]) { - int y = ver[i]; - if (y == c[1]) continue; - cout << c[0] << " " << y << endl; - tmp = y; - break; - } - cout << c[1] << " " << tmp << endl; - return; - } -} -int main() { - int T; - cin >> T; - while (T--) { - solve(); - } - return 0; -}