并查集

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int maxn = 1e4 + 5;
int f[maxn];
int n, m;

inline int Find(int x) { return f[x] == x ? x : f[x] = Find(f[x]); }

signed main(void)
{
    scanf("%d %d", &n, &m);

    for (int i = 1; i <= n; i++)
        f[i] = i;

    for (int i = 1, opt, x, y; i <= m; i++)
    {
        scanf("%d %d %d", &opt, &x, &y);
        if (opt == 1)
            f[Find(x)] = Find(y);
        if (opt == 2)
            Find(x) == Find(y) ? puts("Y") : puts("N");
    }

    return 0;
}
原文地址:https://www.cnblogs.com/lfyzoi/p/10478002.html