Cod sursa(job #1750842)

Utilizator AhileGigel Frone Ahile Data 31 august 2016 11:40:12
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.47 kb
#include<bits/stdc++.h>
using namespace std;
#define in f
#define out g


ifstream f ("disjoint.in");
ofstream g ("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) {

    int rootx = fin(x);
    int rooty = fin(y);
    if(rootx == rooty) {
        out << "DA" << endl;
    } else {
        out << "NU" << endl;
    }
}

int main() {

    in >> n;
    in >> m;
    for(int i = 1; i <= m; i++) {
        in >> code;
        in >> x;
        in >> y;
        if(code == 1) {
            uni(x, y);
        }
        if(code == 2) {
            query(x, y);
        }
    }
    return 0;
}
/*
    if(rootX == rootY)
        return;
    if(ranc[rootX] > ranc[rootY])
        father[rootY] = rootX;
    else if(ranc[rootX] < ranc[rootY])
        father[rootX] = rootY;
    else
    father[rootX] = rootY;
    ranc[rootY]++;

}
*/