[AcWing 4290] 小希的迷宫

image
image

并查集 + 树的判定


点击查看代码
#include<bits/stdc++.h>

using namespace std;

typedef long long LL;

const int N = 1e6 + 10;

int n;
int p[N];

int find(int x)
{
    if (p[x] != x)
        p[x] = find(p[x]);
    return p[x];
}

void merge(int a, int b)
{
    int pa = find(a), pb = find(b);
    p[pa] = pb;
}

void solve()
{
    for (int Case = 1; ; Case ++) {
        int a, b;
        bool ok = true;
        for (int i = 0; i < N; i ++)
            p[i] = i;
        while (cin >> a >> b, a > 0) {
            // 形成环
            if (find(a) == find(b))
                ok = false;
            else
                merge(a, b);
        }
        if (a == -1)
            break;
        cout << (ok ? "Yes" : "No") << endl;
    }
}

signed main()
{
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    solve();

    return 0;
}

  1. 树的定义存在一些争议,对于算法题中的无向图,可以认为,只要无环即是树
posted @ 2022-08-16 17:22  wKingYu  阅读(21)  评论(0编辑  收藏  举报