Cod sursa(job #3268771)

Utilizator aeru1Ianos Alex-Marian aeru1 Data 17 ianuarie 2025 08:27:04
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.94 kb
#include <bits/stdc++.h>

using namespace std;

#define TITLE "disjoint"

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

int Fathers[100002];
int Rang[100002];

int Root(int x)
{
    if(Fathers[x]==x)
        return x;
    return Fathers[x]=Root(Fathers[x]);
}

void Union(int x, int y)
{
    int Rootx=Root(x), Rooty=Root(y);
    if(Rang[Rootx]<Rang[Rooty])
        Fathers[Rootx]=Fathers[Rooty];
    else
        Fathers[Rooty]=Fathers[Rootx];
    if(Rang[Rootx]==Rang[Rooty])
        Rang[Rootx]++;
}

int main()
{
    int n,m;
    f>>n>>m;
    for(int i=1; i<=n; i++)
    {
        Fathers[i]=i;
        Rang[i]=1;
    }
    while(m--)
    {
        int c, x , y;
        f>>c>>x>>y;
        if(c==1)
            Union(x,y);
        else
        {
            if(Root(x)==Root(y))
                g<<"DA";
            else
                g<<"NU";
            g<<'\n';
        }
    }
    return 0;
}