P10179 题解

· · 题解

考虑对每个限制 (u_i,v_i) 连无向边 (u_i,v_i)

算法的时间复杂度为 O(n+m)

#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;

int T, n, m, fa[N];

inline int getfa(int x) {return x == fa[x] ? x : fa[x] = getfa(fa[x]);}

int main() {
    scanf("%d", &T);
    while (T--) {
        scanf("%d%d", &n, &m);
        for (int i = 1; i <= n; ++i) fa[i] = i;
        for (int i = 1, x, y; i <= m; ++i) {
            scanf("%d%d", &x, &y);
            assert(x != y);
            x = getfa(x); y = getfa(y);
            fa[x] = y;
        }
        int cnt = 0; int p[2];
        for (int i = 1; i <= n; ++i) {
            if (getfa(i) != i) continue;
            if (cnt < 2) p[cnt] = i;
            cnt++;
        }
        if (cnt == 1 && n > 1) {
            puts("No");
            continue;
        }
        if (cnt == 1 && n == 1) {
            puts("Yes");
            continue;
        }
        puts("Yes");
        printf("%d %d\n", p[0], p[1]);
        for (int i = 1; i <= n; ++i) {
            if (i == p[0] || i == p[1]) continue;
            if (getfa(i) == p[0]) printf("%d %d\n", i, p[1]);
            else printf("%d %d\n", i, p[0]);
        }
    }
    return 0;
}