Cod sursa(job #2936920)

Utilizator AdelaCorbeanuAdela Corbeanu AdelaCorbeanu Data 9 noiembrie 2022 17:54:04
Problema Paduri de multimi disjuncte Scor 70
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.79 kb
#include <fstream>
#include <vector>


int main()
{
    std::ifstream fin("disjoint.in");
    std::ofstream fout("disjoint.out");

    int n, m;
    fin >> n >> m;

    std::vector<int> ancestor(n + 1);
    for (int i = 1; i <= n; ++i) ancestor[i] = i;

    std::vector<int> rank(n + 1, 1);
    for (int i = 0; i < m; ++i) {
        int op, x, y;
        fin >> op >> x >> y;

        while (ancestor[x] != x || ancestor[y] != y) {
            if (ancestor[x] != x) x = ancestor[x];
            if (ancestor[y] != y) y = ancestor[y];
        }

        if (op == 1) {
            if (rank[x] < rank[y]) ancestor[x] = y;
            else if (rank[x] > rank[y]) ancestor[y] = x;
            else ancestor[x] = y, ++rank[x];
        }
        else fout << (x == y ? "DA" : "NU") << '\n';
    }

    return 0;
}