Cod sursa(job #2965586)

Utilizator victor_gabrielVictor Tene victor_gabriel Data 15 ianuarie 2023 16:47:46
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.1 kb
#include <fstream>

using namespace std;

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

const int DIM = 100001;
int n, m, t, x, y;
int father[DIM];

void init(int vec[]) {
    for (int i = 0; i < DIM; i++)
        vec[i] = -1;
}

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

    while (node != root) {
        int temp = father[node];
        father[node] = root;
        node = temp;
    }

    return root;
}

void join(int node1, int node2) {
    int root1 = get_root(node1);
    int root2 = get_root(node2);

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

bool query(int node1, int node2) {
    return get_root(node1) == get_root(node2);
}

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

    return 0;
}