Cod sursa(job #2147029)

Utilizator FlorinHajaFlorin Gabriel Haja FlorinHaja Data 28 februarie 2018 13:21:42
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.8 kb
#include <fstream>

using namespace std;

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

const int nmax = 100005;
int tt[nmax], gr[nmax], i, j, n, m, tip, x, y, t;

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;
}

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

int main() {
    f >> n >> m;
    for (i = 1; i <= n; i++)
        tt[i] = i, gr[i] = 1;

    while (m--) {
        f >> t >> x >> y;
        if (t == 1)
            join(update(x), update(y));
        else if (update(x) != update(y))
            g << "NU\n";
        else g << "DA\n";
    }

    return 0;
}