Cod sursa(job #3281529)

Utilizator UengineDavid Enachescu Uengine Data 2 martie 2025 02:03:03
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <fstream>

using namespace std;

ifstream cin("disjoint.in");
ofstream cout("disjoint.out");

const int N = 1e5 + 5;
vector<int> root(N), depth(N);

int find_root(int nod) {
    if (root[nod] == nod)
        return nod;
    return root[nod] = find_root(root[nod]);
}

void unite(int node1, int node2) {
    node1 = find_root(node1);
    node2 = find_root(node2);
    if (depth[node2] < depth[node1])
        root[node2] = node1;
    else if (depth[node1] < depth[node2])
        root[node1] = node2;
    else {
        root[node1] = node2;
        depth[node2]++;
    }
}

int main() {
    int n, m;
    cin >> n >> m;
    depth.assign(n + 1, 1);
    for (int i = 1; i <= n; i++)
        root[i] = i;
    for (int i = 1; i <= m; i++) {
        int cer, node1, node2;
        cin >> cer >> node1 >> node2;
        if (cer == 1)
            unite(node1, node2);
        else if (find_root(node1) == find_root(node2))
            cout << "DA\n";
        else
            cout << "NU\n";
    }
    return 0;
}