Cod sursa(job #3193004)

Utilizator victor_gabrielVictor Tene victor_gabriel Data 13 ianuarie 2024 18:55:01
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <fstream>

using namespace std;

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

const int DIM = 100010;

int n, m;
int father[DIM];

int getRoot(int node) {
    while (father[node] > 0)
        node = father[node];
    return node;
}

void join(int node1, int node2) {
    int root1 = getRoot(node1);
    int root2 = getRoot(node2);
    if (root1 == root2)
        return;

    if (father[root1] <= father[root2]) {
        father[root1] += father[root2];
        father[root2] = root1;
    } else {
        father[root2] += father[root1];
        father[root1] = root2;
    }
}

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

    for (int i = 1; i <= n; i++)
        father[i] = -1;

    for (int i = 1; i <= m; i++) {
        int cmd, x, y;
        fin >> cmd >> x >> y;
        if (cmd == 1) {
            join(x, y);
        } else {
            fout << (getRoot(x) == getRoot(y) ? "DA" : "NU") << '\n';
        }
    }

    return 0;
}