Cod sursa(job #2166083)

Utilizator Andrei17Andrei Pascu Andrei17 Data 13 martie 2018 15:27:49
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.81 kb
#include <fstream>

using namespace std;

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

const int N = 100001;

int n, m, t[N], nr[N];

int radacina(int x) {
    if (t[x] == 0) return x;
    t[x] = radacina(t[x]);
    return t[x];
}

void query(int x, int y) {
    if (radacina(x) == radacina(y)) out << "DA\n";
    else out << "NU\n";
}

void reunion(int x, int y) {
    int rx = radacina(x), ry = radacina(y);

    if (nr[rx] > nr[ry]) {
        t[ry] = rx;
        nr[rx] += nr[ry];
    }
    else {
        t[rx] = ry;
        nr[ry] += nr[rx];
    }
}

int main()
{
    in >> n >> m;

    std::fill(nr + 1, nr + n + 1, 1);
    int op, x, y;
    for (int i = 0; i < m; i++) {
        in >> op >> x >> y;
        if (op == 1) reunion(x, y);
        if (op == 2) query(x, y);
    }
    in.close();
    out.close();
}