Cod sursa(job #3309580)

Utilizator andiRTanasescu Andrei-Rares andiR Data 6 septembrie 2025 15:17:06
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <iostream>
#include <fstream>

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

const int Nmax=1e5+5;

int n, m;

struct DSU{
    int rep[Nmax];
    int sz[Nmax];

    DSU(int n){
        for (int i=1; i<=n; i++){
            rep[i]=i;
            sz[i]=1;
        }
    }

    int get_rep(int node){ // returneaza reprezentantul suprem pt node
        if (rep[node]==node)
            return node;
        return rep[node]=get_rep(rep[node]); // path compression
    }

    bool same_set(int a, int b){
        int ra=get_rep(a);
        int rb=get_rep(b);

        return ra==rb;
    }

    void join(int a, int b){
        int ra=get_rep(a);
        int rb=get_rep(b);

        if (ra==rb)
            return;

        if (sz[rb]>sz[ra])
            swap(ra, rb);

        rep[rb]=ra;
        sz[rb]+=sz[ra];
    }
};

int main(){

    fin>>n>>m;

    DSU dsu(n);
    
    int t, a, b;
    while (m--){
        fin>>t>>a>>b;

        if (t==1)
            dsu.join(a, b);
        else if (dsu.same_set(a, b))
            fout<<"DA\n";
        else fout<<"NU\n";
    }

    return 0;
}