4 7
2 1 2
1 1 2
2 1 2
1 3 4
2 1 4
1 2 3
2 1 4
#include <iostream>
 
using namespace std;
 
const int N = 10010;
 
int n, m;
int f[N];
 
int find(int x){
    if (f[x] != x) return f[x] = find(f[x]);
    return f[x];
}
int main(){
    scanf("%d%d", &n, &m);
     
    for (int i = 1; i <= n; i ++ ) f[i] = i;
    while (m -- ){
        int a, b, t;
        scanf("%d%d%d", &t, &a, &b);
         
        if (t == 1){
            f[find(a)] = find(b);
        }
        else {
            if (find(a) == find(b)) puts("Y");
            else puts("N");
        }
    }
     
    return 0;
}
原文:https://www.cnblogs.com/Iamcookieandyou/p/13372735.html