Cod sursa(job #3351257)

Utilizator eric_dragosDragos Eric eric_dragos Data 18 aprilie 2026 10:47:58
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <bits/stdc++.h>
#define ll long long
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
struct DSU{
    vector<int> root;
    vector<int> rang;
    DSU(int n){
        root.resize(n+1);
        rang.resize(n+1, 0);
        for(int i = 1; i<=n; i++)root[i] = i;
    }
    int find(int x){
        int parent = root[x];
        if(root[parent] != root[x]) return root[x] = find(parent);
        return parent;  
    }
    void unite(int x, int y){
        int rx = find(x), ry = find(y);
        if(rx == ry) return;

        if(rang[rx] < rang[ry])swap(rx, ry);
        root[ry] = rx;
        if(rang[rx] == rang[ry]) rang[rx]++;
    }
};
int main(){
    int n,m;
    fin >> n >> m;
    DSU dsu(n);
    while(m--){
        int x,y,c;
        fin >> c >> x >> y;
        if(c == 1){
            dsu.unite(x,y);
        }
        else{
            fout << ((dsu.find(x) == dsu.find(y)) ? "DA\n" : "NU\n");
        }
    }

    return 0;
}