Cod sursa(job #2854013)

Utilizator VladTZYVlad Tiganila VladTZY Data 20 februarie 2022 20:26:42
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.11 kb
#include <fstream>

#define NMAX 100005

using namespace std;

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

int n, questions, type, a, b;
int root[NMAX];

int getRoot(int x) {
    int node = x;

    while (root[x] > 0)
        x = root[x];

    while (root[node] > 0) {
        int saveNode = node;

        node = root[node];
        root[saveNode] = x;
    }

    return x;
}

void joinRoots(int x, int y) {

    if (root[x] * -1 > root[y] * -1) {

        root[y] = root[y] + root[x];
        root[x] = y;

    } else {

        root[x] = root[x] + root[y];
        root[y] = x;
    }
}

int main()
{
    f >> n >> questions;

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

    while (questions--) {
        f >> type >> a >> b;

        int rootA = getRoot(a);
        int rootB = getRoot(b);

        if (type == 1) {

            if (rootA != rootB)
                joinRoots(rootA, rootB);

            continue;
        }

        if (rootA == rootB)
            g << "DA\n";
        else
            g << "NU\n";
    }

    return 0;
}