Cod sursa(job #1750906)

Utilizator AhileGigel Frone Ahile Data 31 august 2016 14:07:48
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include<bits/stdc++.h>
using namespace std;
#define FIN "disjoint.in"
#define FOUT "disjoint.out"


int n;
int m;
int x;
int y;
int code;
int aux;
int father[100010];
int rang[100010];

int fin(int x) {

    if(father[x] == 0) {
        return x;
    } else {
        return fin(father[x]);
    }

}

int uni (int x, int y) {

    int rooty;
    int rootx;
    rooty = fin(y);
    rootx = fin(x);
    if(rootx == rooty) {
        return 0;
    }
    if(rang[rootx] > rang[rooty]) {
        father[rooty] = rootx;
    } else {
        if(rang[rootx] < rang[rooty]) {
            father[rootx] = rooty;
        } else {
            father[rootx] = rooty;
            rang[rooty]++;
        }
    }

}

int query (int x, int y) {

    freopen(FOUT,"w",stdout);
    int rootx = fin(x);
    int rooty = fin(y);
    if(rootx == rooty) {
        printf("DA\n");
    } else {
        printf("NU\n");
    }
}

int main() {

    freopen(FIN, "r",stdin);
    scanf("%d %d", &n,&m);

    for(int i = 1; i <= m; i++) {
        scanf("%d %d %d", &code,&x,&y);
        if(code == 1) {
            uni(x, y);
        }
        if(code == 2) {
            query(x, y);
        }
    }
    return 0;
}