Cod sursa(job #3350500)

Utilizator eric_dragosDragos Eric eric_dragos Data 8 aprilie 2026 19:52:32
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.31 kb
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
#define N 100005
int n,m;
// int root[N];
// int rang[N];

struct dsu{
    vector<int> root;
    vector<int> rang;
    dsu(int n){
        root.resize(n);
        rang.resize(n);
        for(int i = 1; i<=n; i++){
            root[i] = i;
            rang[i] = 0;
        }
    }
    int find(int x){
        int parent = root[x];
        if(root[parent] != parent) return root[x] = find(parent);
        else return parent;
    }

    void unire(int x, int y){
        int rootX = find(x);
        int rootY = find(y); 
        if(rootX == rootY) return;
        if(rang[rootX] < rang[rootY]){
            root[rootX] = rootY;
        }
        else if(rang[rootX] > rang[rootY]){
            root[rootY] = rootX;
        }
        else{
            root[rootX] = rootY;
            rang[rootY]++;
        }

    }
};

int main(){
    fin >> n >> m;
    dsu d(n);
    while(m--){
        int c,x,y;
        fin >> c >> x >> y;
        if(c == 1) d.unire(x,y);
        else{
            if(d.find(x) == d.find(y)) fout << "DA\n";
            else fout << "NU\n";
        }
    }
    // for(int i = 1; i<=n; i++) cout << root[i] << ' ';

    return 0;
}