博客园 首页 私信博主 显示目录 隐藏目录 管理

【模板】并查集

#include<bits/stdc++.h>

using namespace std;

const int N = 10010;

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

template <typename T>
T read(){
    T N(0), F(1);
    char C = getchar();
    for(; !isdigit(C); C = getchar()) if(C == '-') F = -1;
    for(; isdigit(C); C = getchar()) N = N*10 + C-48;
    return N*F;
}

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

void mix(int x, int y){
    if(x == y) return;
    if(r[x] < r[y]){
        fa[x] = y;
    }
    else{
        fa[y] = x;
        if(r[x] == r[y]) r[x]++;
    }
}

int main(){
    n = read<int>();
    m = read<int>();

    for(int i = 1; i <= n; i++) fa[i] = i, r[i] = 0;

    for(int i = 1; i <= m; i++){
        int z, x, y;
        z = read<int>();
        x = read<int>();
        y = read<int>();
        
        if(z == 1){
            int fx = find(fa[x]);
            int fy = find(fa[y]);
            mix(fx, fy);
        }
        else{
            if(find(fa[x]) == find(fa[y])) puts("Y");
            else puts("N");
        }
    }    
    return 0;
}
posted @ 2017-10-14 23:25  Hanser  阅读(109)  评论(0编辑  收藏  举报