Cod sursa(job #3267152)

Utilizator cris71Vlad Bogdan Cristian cris71 Data 11 ianuarie 2025 10:02:33
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.98 kb
#include <bits/stdc++.h>
using namespace std;
int const lmax=1e5+7;
ifstream fin ("disjoint.in");
ofstream fout ("disjoint.out");
int t[lmax],h[lmax],n,m;
int find_(int x)
{
    if(t[x]==0)return x;
    t[x]=find_(t[x]);
    return t[x];
}
void unite(int x, int y)
{
    x=find_(x);
    y=find_(y);
    if(x==y)return ;
    if(h[x]<h[y])
    {
        h[x]=h[y];
        t[x]=y;
    }
    else if(h[x]>h[y])
    {
        h[x]=h[y];
        t[y]=x;
    }
    else if(h[x]==h[y])
    {
        h[x]=h[y]+1;
        h[y]=h[x];
        t[x]=y;///aleatoriu
    }
}
int main()
{
    fin>>n>>m;
    for(int i=0;i<m;i++)
    {
        int op,x,y;
        fin>>op>>x>>y;
        if(op==1)
        {
            unite(x,y);
        }
        else if (op==2)
        {
            if(find_(x)==find_(y))
            {
                fout<<"DA\n";
            }
            else fout<<"NU\n";
        }
    }
    fin.close();
    fout.close();
    return 0;
}