Cod sursa(job #3168711)

Utilizator andystarzSuna Andrei andystarz Data 13 noiembrie 2023 09:26:20
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <iostream>
#include <fstream>

using namespace std;
int papi[100005];
int rang[100005];
void join(int x, int y)
{
    if (rang[x]<=rang[y])
        swap(x, y);
    papi[y]=x;
    if (rang[x]==rang[y])
        rang[y]++;
}
int quewy(int x)
{
    int nod=x, check;
    while (nod!=papi[nod])
    {
        nod=papi[nod];
    }
    ///gasim taticul lui x
    while (papi[x]!=x)
    {
        check=papi[x];
        papi[x]=nod;
        x=check;
    }
    return nod;
}
int main()
{
    ifstream cin ("disjoint.in");
    ofstream cout ("disjoint.out");
    int n, q, tip, x, y;
    cin>>n>>q;
    for (int i=1; i<=n; i++) { papi[i]=i; rang[i]=1; }
    for (int i=1; i<=q; i++)
    {
        cin>>tip>>x>>y;
        if (tip==1)
        {
            if (quewy(x)!=quewy(y))
            {
                join(quewy(x), quewy(y));
            }
        }
        else if (tip==2)
        {
            if (quewy(x)==quewy(y)) cout<<"DA"<<'\n';
            else cout<<"NU"<<'\n';
        }
    }
}