Cod sursa(job #3278038)

Utilizator Cris24dcAndrei Cristian Cris24dc Data 18 februarie 2025 16:53:49
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.51 kb
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

struct dsu {
    vector<int> root;
    vector<int> height;

    dsu(int n) {
        height.resize(n+1, 0);
        root.resize(n+1);
        for (int i = 1; i <= n; i++) {
            root[i] = i;
        }
    }

    int findRoot(int node) {
        if (node != root[node]) {
            root[node] = findRoot(root[node]);
        }
        return root[node];
    }

    void unionNodes(int u, int v) {
        int rootU = findRoot(u);
        int rootV = findRoot(v);
        if(rootU == rootV) {
            return;
        }
        if(height[rootU] < height[rootV]) {
            root[rootU] = rootV;
        }
        else if(height[rootU] > height[rootV]) {
            root[rootV] = rootU;
        }
        else {
            root[rootU] = rootV;
            height[rootV]++;
        }
    }

    bool areConnected(int u, int v) {
        return findRoot(u) == findRoot(v);
    }
};

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

    int nodes, instr;
    fin >> nodes >> instr;

    auto myDsu = dsu(nodes);

    for (int i = 0; i < instr; i++) {
        int code, u, v;
        fin >> code >> u >> v;
        if (code == 1) {
            myDsu.unionNodes(u, v);
        }
        else {
            if (myDsu.areConnected(u, v)) {
                fout << "DA" << endl;
            }
            else {
                fout << "NU" << endl;
            }
        }
    }

    fin.close();
    fout.close();

    return 0;
}