Cod sursa(job #3286459)

Utilizator nusuntvictorVictor Stefan nusuntvictor Data 14 martie 2025 11:12:57
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.93 kb
#include <bits/stdc++.h>

using namespace std;

ifstream f("disjoint.in");
ofstream g("disjoint.out");


vector<int>tata(100005),height(100005);

int get_root(int nod){
    if(nod!=tata[nod]){
        tata[nod]=get_root(tata[nod]);
    }
    return tata[nod];
}

void unite(int x, int y){
    int rx=get_root(x);
    int ry=get_root(y);
    if(height[rx]>height[ry])
        tata[ry]=rx;
    else if(height[rx]<height[ry])
            tata[rx]=ry;
    else{
        tata[ry]=rx;
        height[rx]++;
    }
}

void reset(int n){
    for(int i=1; i<=n; ++i){
        tata[i]=i;
        height[i]=1;
    }

}
int main()
{
    int n,task;
    f>>n>>task;
    reset(n);
    for(int i=1; i<=task; ++i)
    {
        int op,x,y;
        f>>op>>x>>y;
        if(op==1)
            unite(x,y);
        else if(get_root(x)==get_root(y))
                g<<"DA\n";
        else g<<"NU\n";
    }
    return 0;
}