Cod sursa(job #1828430)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 13 decembrie 2016 12:20:13
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include <fstream>

using namespace std;

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

int grad[100005], tt[100005];
int n, m, i, c, x, y;

void join(int x, int y) {
    if (grad[x] > grad[y])
        tt[y] = x;
    else tt[x] = y;
    if (grad[x] == grad[y])
        grad[y]++;
}

int update(int x) {
    int r = x, y;

    while (tt[r] != r)
        r = tt[r];
    while (tt[x] != x) {
        y = tt[x];
        tt[x] = r;
        x = y;
    }
    return r;
}

int main() {
    f >> n >> m;
    for (i = 1; i <= n; i++)
        tt[i] = i, grad[i] = 1;
    while (m--) {
        f >> c >> x >> y;
        if (c == 2) {
            if (update(x) == update(y))
                g << "DA\n";
            else g << "NU\n";
        }
        else {
            if (update(x) != update(y))
                join(x, y);
        }
    }
    return 0;
}