Cod sursa(job #3303438)

Utilizator Luca_georgescuLuca Georgescu Luca_georgescu Data 15 iulie 2025 16:15:59
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include <bits/stdc++.h>

using namespace std;

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

const int nmax=100005;
int t[nmax],h[nmax],n,m,c,x,y;

void init(int n)
{
    for (int i=1; i<=n; i++ )
    {
        t[i]=i;
        h[i]=1; // h arbore
    }
}

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

void unif(int x, int y)
{
    x=root(x);
    y=root(y);

    if ( h[x]<h[y] )
        t[x]=y;
    else
    {
        t[y]=x;
        if ( h[x]==h[y] )
            h[x]++;
    }
}

int main()
{
    f >> n >> m;

    init(n);

    for (int i=1; i<=m; i++ )
    {
        f >> c >> x >> y;
        if ( c==1 )
            unif(x,y);
        else
        {
            if ( root(x)==root(y) )
                g << "DA" << '\n';
            else g << "NU" << '\n';
        }
    }
    return 0;
}