Cod sursa(job #3003617)

Utilizator GoofyAhBalea Gabriel GoofyAh Data 15 martie 2023 20:21:09
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.78 kb
#include <bits/stdc++.h>

using namespace std;

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

int n,m,t[100001], rang[100001];

int rep(int nod){
    int aux;
    if (t[nod]!=nod) {
        aux=rep(t[nod]);
        t[nod]=aux;
    }
    return t[nod];
}

void uniune(int x,int y){
    if (rang[x]<=rang[y]) {
        t[rep(x)]=rep(y);
        rang[x]++;
    }
    else {
        t[rep(x)]=rep(y);
        rang[y]++;
    }
}

int main(){
    int q, x, y;
    fin >> n >> m;
    for (int i=1;i<=n;i++) t[i]=i;
    for (int i=1;i<=m;i++){
        fin >> q >> x >> y;
        if (q==1) {
            uniune(x,y);
        }
        if (q==2){
            if (rep(x)==rep(y)) fout << "DA\n";
            else fout << "NU\n";
        }
    }
}