Cod sursa(job #1684222)

Utilizator razvandRazvan Dumitru razvand Data 10 aprilie 2016 21:38:06
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <iostream>
#include <fstream>
#define MAX 100003

using namespace std;

ifstream in("disjoint.in");
ofstream out("disjoint.out");

int T[MAX];
int H[MAX];

int father(int x) {
    if(T[x] == x)
        return x;
    T[x] = father(T[x]);
    return T[x];
}

void un(int x, int y) {
    int fath1 = father(x);
    int fath2 = father(y);
    if(H[fath1] == H[fath2]) {
        T[fath2] = fath1;
        H[fath1++];
        return;
    }
    if(H[fath1] < H[fath2]) {
        T[fath1] = fath2;
        return;
    } else {
        T[fath2] = fath1;
        return;
    }
}

int main() {

    int n,m,t,x,y;
    in >> n >> m;

    for(int i = 1; i <= n; i++)
        T[i] = i;

    for(int i = 1; i <= m; i++) {

        in >> t >> x >> y;

        if(t == 1) {

            un(x, y);

        } else {

            if(father(x) == father(y)) {
                out << "DA" << '\n';
            } else {
                out << "NU" << '\n';
            }

        }

    }

    return 0;
}