Cod sursa(job #3204598)

Utilizator razvan242Zoltan Razvan-Daniel razvan242 Data 17 februarie 2024 09:55:05
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <fstream>
#include <vector>

using namespace std;

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

int n, queries;
vector<int> root, height;

void initializeRoots() {
    for (int i = 1; i <= n; ++i) {
        root[i] = i;
    }
}

void readData() {
    fin >> n >> queries;
    root = vector<int>(n + 1);
    height = vector<int>(n + 1);
    initializeRoots();
}

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

void unite(int x, int y) {
    int rootX = getRoot(x);
    int rootY = getRoot(y);
    if (rootX != rootY) {
        if (height[rootX] <= height[rootY]) {
            root[rootX] = rootY;
            if (height[rootX] == height[rootY]) {
                ++height[rootY];
            }
        }
        else {
            root[rootY] = rootX;
        }
    }
}

bool query(int x, int y) {
    return getRoot(x) == getRoot(y);
}

void solveQueries() {
    int task, x, y;
    while (queries--) {
        fin >> task >> x >> y;
        if (task == 1) {
            unite(x, y);
        }
        else {
            if (query(x, y)) {
                fout << "DA\n";
            }
            else {
                fout << "NU\n";
            }
        }
    }
}

int main()
{
    readData();
    solveQueries();

    fin.close();
    fout.close();
    return 0;
}