Cod sursa(job #3350428)

Utilizator eric_dragosDragos Eric eric_dragos Data 7 aprilie 2026 19:42:26
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 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];

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

    return 0;
}