Cod sursa(job #2383634)

Utilizator MateiTrandafirMatei Trandafir MateiTrandafir Data 19 martie 2019 18:18:12
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.76 kb
#include <fstream>

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

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

inline void reunion(int x, int y) {
    int rx = root(x);
    int ry = root(y);
    if (nr[rx] < nr[ry]) {
        nr[ry] += nr[rx];
        t[rx] = ry;
    } else {
        nr[ry] += nr[rx];
        t[ry] = rx;
    }
}

inline bool check(int x, int y) {
    return root(x) == root(y);
}

int main() {
    std::ifstream in("disjoint.in");
    std::ofstream out("disjoint.out");
    int i, x, y, z;
    in >> n >> m;
    for (i = 1; i <= n; ++i) nr[i] = 1;
    for (i = 0; i < m; ++i) {
        in >> z >> x >> y;
        if (z == 1) reunion(x, y);
        else out << (check(x, y) ? "DA" : "NU") << '\n';
    }
    return 0;
}