Cod sursa(job #3280368)

Utilizator Alex_DumitrascuAlex Dumitrascu Alex_Dumitrascu Data 26 februarie 2025 11:54:21
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <bits/stdc++.h>

using namespace std;

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

int root[100005], level[100005];

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

int main()
{
    fin.tie(0); fin.sync_with_stdio(false);
    int n, m, op, x, y; fin>>n>>m;
    for (int i=1; i<=n; i++) {
        root[i]=i;
        level[i]=1;
    }
    for (int i=1; i<=m; i++) {
        fin>>op>>x>>y;
        int root_x = root[x], root_y = root[y];
        root_x = find_root(root_x); root_y = find_root(root_y);
        while (root[root_y]!=root_y) {
            root_y = root[root_y];
        }
        if (op == 1) {
            
            int dad, son;
            if (level[root_x]<level[root_y]) {
                dad = root_x;
                son = root_y;
            }
            else {
                dad = root_y;
                son = root_x;
            }
            level[dad]++;
            root[son] = dad;
        }
        if (op == 2) {
            if (root_x==root_y) fout<<"DA\n";
            else fout<<"NU\n";
        }
    }
    return 0;
}