Cod sursa(job #2978936)

Utilizator CobzaruAntonioCobzaru Paul-Antonio CobzaruAntonio Data 14 februarie 2023 17:29:36
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <fstream>

using namespace std;
ifstream cin ("disjoint.in");
ofstream cout ("disjoint.out");
int n,m;
int rang[100005];
int rad[100005];
int gasesterad (int nod)
{
    int rasp,aux;
    rasp = nod;
    aux = nod;
    while (rad[rasp]!=rasp)
        rasp = rad[rasp];
    while (rad[aux]!=aux)
    {
        int aux2;
        aux2 = rad[aux];
        rad[aux] = rasp;
        aux = aux2;
    }
    return rasp;
}
void uneste (int x,int y)
{
    if (rang[x] > rang[y])
        rad[y] = x;
    else if (rang[y] > rang[x])
        rad[x] = y;
    else
    {
        rad[y] = x;
        rang[x]++;
    }
}
int main()
{
    ios::sync_with_stdio(false);
    cin.tie(0);
    cout.tie(0);
    cin >> n >> m;
    int i,j;
    for (i=1;i<=n;i++)
    {
        rang[i] = 1;
        rad[i] = i;
    }
    for (i=1;i<=m;i++)
    {
        int t,x,y;
        cin >> t >> x >> y;
        x = gasesterad(x);
        y = gasesterad(y);
        if (t == 1)
            uneste(x,y);
        else
        {
            if (x!=y)
                cout << "NU" << '\n';
            else
                cout << "DA" << '\n';
        }
    }
    return 0;
}