Cod sursa(job #1401742)

Utilizator AnduuFMI Alexandru Banu Anduu Data 26 martie 2015 09:12:22
Problema Paduri de multimi disjuncte Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.31 kb
#include <fstream>

#define NMAX 100001
using namespace std;

int T[NMAX], H[NMAX];

int rep(int nod) {
    while (T[nod])
        nod = T[nod];
    return nod;
}

void compresie(int nod, int r) {
    int tata;

    while (T[nod]) {
        tata = T[nod];
        T[nod] = r;
        nod = tata;
    }
}

bool interogare(int x, int y) {
    if (rep(x) == rep(y))
        return 1;
    return 0;
}

void reuniune(int x, int y) {
    int a, b;

    a = rep(x);
    b = rep(y);

    if (H[a] == H[b]) {
        T[x] = y;
        H[rep(y)]++;
        compresie(x, b);
        compresie(y, b);
    }
    else if (H[x] < H[y]) {
            T[x] = y;
            compresie(x, b);
            compresie(y, b);
    }
        else {
            T[y] = x;
            compresie(y, a);
            compresie(x, a);
        }
}

int main() {
    int i, n, m;

    ifstream in("disjoint.in");
    in >> n >> m;
    int t, x, y, ok;
    ofstream out("disjoint.out");
    for (i = 1; i <= m; i++) {
        in >> t >> x >> y;
        if (t == 1)
            reuniune (x, y);
        else {
            ok = interogare (x, y);
            if (!ok)
                out << "NU\n";
            else out << "DA\n";
        }
    }
    out.close();
    in.close();

    return 0;
}