Cod sursa(job #3358063)

Utilizator Hutanu_MaiaHutanu Ioana-Maia Hutanu_Maia Data 14 iunie 2026 13:12:54
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int n,m,p[100005],h[100005];
int find(int nod)
{
    int cop=nod,rez;
    while(nod!=p[nod])
        nod=p[nod];
    rez=nod;
    nod=cop;
    while(nod!=p[nod])
    {
        int c=p[nod];
        p[nod]=rez;
        nod=c;
    }
    return rez;
}
void unite(int a,int b)
{
    if(a==b)
        return;
    if(h[a]<h[b])
        swap(a,b);
    else if(h[a]==h[b])
    {
        h[a]++;
        h[b]++;
    }
    p[b]=a;
}
int main()
{
    fin>>n>>m;
    int c,x,y;
    for(int i=1; i<=n; i++)
    {
        p[i]=i;
        h[i]=1;
    }
    for(int i=1; i<=m; i++)
    {
        fin>>c>>x>>y;
        if(c==1)
            unite(find(x),find(y));
        else
        {
            if(find(x)==find(y))
                fout<<"DA"<<'\n';
            else
                fout<<"NU"<<'\n';
        }
    }
    return 0;
}