Cod sursa(job #3291949)

Utilizator radugheoRadu Mihai Gheorghe radugheo Data 6 aprilie 2025 12:59:58
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <fstream>

using namespace std;

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

int n, m, x, y, cod;
int t[100005], rang[100005];

int root(int k) {
    if (t[k] == 0) {
        return k;
    }
    else {
        int x = root(t[k]);
        t[k] = x;
        return x;
    }
}

void combine(int x, int y) {
    int rx = root(x), ry = root(y);
    if (rx != ry) {
        if (rang[rx] > rang[ry]) {
            t[ry] = rx;
        }
        else if (rang[rx] < rang[ry]) {
            t[rx] = ry;
        }
        else {
            t[ry] = rx;
            rang[rx]++;
        }
    }
}

int main(){
    fin >> n >> m;
    while (m--) {
        fin >> cod >> x >> y;
        if (cod == 1) {
            combine(x, y);
        }
        else {
            int rx = root(x), ry = root(y);
            if (rx == ry) {
                fout << "DA\n";
            }
            else {
                fout << "NU\n";
            }
        }
    }
    return 0;
}