超时三个点

P3367 【模板】并查集

KagurazakaKano @ 2018-08-22 21:17:23

#include <cstdio>
#include <cmath>
#include <algorithm>

using namespace std;

int f[10005];

int getF(int x){
    if(f[x] == x){
        return x;
    } else {
        return getF(f[x]);
    }
}

void merg(int x, int y){
    int fX = getF(x);
    int fY = getF(y);
    if(fX != fY){
        f[fY] = f[x];
    }
    return;
}

void iG(int x, int y){
    if(getF(x) == getF(y)){
        printf("Y\n");
    } else {
        printf("N\n");
    }
    return;
}

int main(){
    int n,m;
    int z,x,y;
    scanf("%d%d",&n,&m);
    for(int i = 1; i <= n; i++){
        f[i] = i;
    }
    for(int i = 1; i <= m; i++){
        scanf("%d%d%d",&z,&x,&y);
        if(z == 1){
            merg(x,y);
        } else {
            iG(x, y);
        }
    }
    return 0;
}

by 捻红尘似水 @ 2018-08-22 21:20:50

路径压缩


by hellomath @ 2018-08-22 21:21:12

@KagurazakaKano 加路径压缩:

int getF(int x){
    if(f[x] == x){
        return x;
    } else {
        return f[x] = getF(f[x]);
    }
}

by KagurazakaKano @ 2018-08-22 21:28:10

@larryzhong 感谢!


by 7KByte @ 2018-09-25 21:51:35

%%%


|