并查集

#include<bits/stdc++.h>
#define ri register int
#define ll long long
#define fast ios::sync_with_stdio(0), cin.tie(0), cout.tie(0)
using namespace std;
const inline int read(){
    int k = 0, f = 1; char c = getchar();
    for(;!isdigit(c); c = getchar())
        if(c == '-') f = -1;
    for(;isdigit(c); c = getchar())
        k = k * 10 + c - '0';
    return k * f;
}
int n, m, f[10005];
int find(int x){
    if(x == f[x]) return x;
    return f[x] = find(f[x]);//路径压缩 
}
int main(){
    n = read(), m = read();
    for(ri i = 1; i <= n; ++i)
        f[i] = i;
    for(ri i = 1; i <= m; ++i){
        ri z, x, y;
        z = read(), x = read(), y = read();
        int a = find(x), b = find(y);
        if(z == 1)
            f[a] = b;//合并 
        else{
            if(a == b)
                printf("Y\n");
            else
                printf("N\n");
        }
    }
    return 0;
}

 

posted @ 2020-03-26 14:52  kojoker  阅读(195)  评论(0)    收藏  举报