Cod sursa(job #3306029)

Utilizator mtcmtcmtc mtc mtcmtc Data 6 august 2025 19:47:34
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.91 kb
#include <fstream>

using namespace std;
ifstream cin("disjoint.in");
ofstream cout("disjoint.out");
const int maxn=1e5+5;
int n,m,tata[maxn],h[maxn];
//returneaza reprezentantul multimii lui x (adc radacina componentei)
int get_root(int x){
    if(x==tata[x]) return x;
    return tata[x]=get_root(tata[x]);
}
bool in_same_component(int x,int y){
    return get_root(x)==get_root(y);
}
void join(int x,int y){
    x=get_root(x);
    y=get_root(y);
    if(x==y) return;
    if(h[x]<h[y]) swap(x,y);
    if(h[x]==h[y]) h[x]++;
    tata[y]=x;
}
int main()
{
    cin>>n>>m;
    for(int i=1;i<=n;i++){
        tata[i]=i;
        h[i]=1;
    }
    int c,x,y;
    for(int i=1;i<=m;i++){
        cin>>c>>x>>y;
        if(c==1){
            join(x,y);
        }
        else{
            if(in_same_component(x,y)) cout<<"DA\n";
            else cout<<"NU\n";
        }
    }
    return 0;
}