Cod sursa(job #3280364)

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

using namespace std;

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

int root[100005], level[100005];

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];
        while (root[root_x]!=root_x) {
            root_x = root[root_x];
        }
        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;
}