Cod sursa(job #2354764)

Utilizator ioana_marinescuMarinescu Ioana ioana_marinescu Data 25 februarie 2019 16:07:06
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.9 kb
#include <fstream>

const int MAX_N = 100000;

using namespace std;

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

int tata[MAX_N + 5], cnt[MAX_N + 5];

int rad(int x) {
    if(tata[x] == 0)
        return x;
    else
        tata[x] = rad(tata[x]);
    return tata[x];
}

void join(int x, int y) {
    x = rad(x);
    y = rad(y);

    if(x == y)
        return;

    if(cnt[x] > cnt[y])
        swap(x, y);

    tata[x] = y;
    cnt[y] += cnt[x];
}

int query(int x, int y) {
    return (rad(x) == rad(y));
}

int main() {
    int n, m;
    fin >> n >> m;

    for(int i = 1; i <= n; i++) {
        tata[i] = 0;
        cnt[i] = 1;
    }
    for(int i = 1; i <= m; i++) {
        int op, x, y;
        fin >> op >> x >> y;

        if(op == 1)
            join(x, y);
        else
            fout << (query(x, y) == 1 ? "DA\n" : "NU\n");
    }
}