Cod sursa(job #2896954)

Utilizator mihnea.tTudor Mihnea mihnea.t Data 1 mai 2022 18:07:34
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.46 kb
#include <bits/stdc++.h>

#define INF ((int)1e9)
#define NMAX ((int)1e5)

using namespace std;

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

int n, m;

int conex_comp[NMAX + 1];
int conex_rank[NMAX + 1];

int get_root(int node) {
    if (conex_comp[node] == node) {
        return node;
    }

    int new_root = get_root(conex_comp[node]);
    conex_comp[node] = new_root;
    return new_root;
}

int unite(int a, int b) {
    int root_a = get_root(a);
    int root_b = get_root(b);

    if (root_a == root_b) {
        // The nodes are already in the same component
        return -1;
    }

    // Otherwise, connect the graphs
    if (conex_rank[root_a] < conex_rank[root_b]) {
        conex_comp[root_a] = root_b;
    } else {
        conex_comp[root_b] = root_a;
    }

    if (conex_rank[root_a] == conex_rank[root_b]) {
        ++conex_rank[root_b];
    }

    return 0;
}

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

    for (int i = 1; i <= n; ++i) {
        conex_comp[i] = i;
        conex_rank[i] = 1;
    }

    for (int i = 0; i < m; ++i) {
        int type, src, dest;
        fin >> type >> src >> dest;

        switch (type) {
            case 1:
                unite(src, dest);
                break;
            
            case 2:
                if (get_root(src) == get_root(dest)) {
                    fout << "DA\n";
                } else {
                    fout << "NU\n";
                }

                break;
        }
    }

    return 0;
}