Cod sursa(job #2928070)

Utilizator CobzaruAntonioCobzaru Paul-Antonio CobzaruAntonio Data 22 octombrie 2022 08:55:17
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.01 kb
#include <fstream>

using namespace std;
ifstream fin ("disjoint.in");
ofstream fout ("disjoint.out");
int T[100005],R[100005];
int t,x,y,i,n,m;
int root (int x)
{
    int answ,aux;
    answ = x;
    while (T[answ]!=answ)
        answ = T[answ];
    while (T[x]!=x)
    {
        aux = T[x];
        T[x] = answ;
        x = aux;
    }
    return answ;
}
void unite (int x,int y)
{
    if (R[x] == R[y])
    {
        T[x] = y;
        R[y]++;
    }
    else if (R[x] > R[y])
        T[y] = x;
    else
        T[x] = y;
}
int main()
{
    fin >> n >> m;
    for (i=1;i<=n;i++)
    {
        T[i] = i;
        R[i] = 1;
    }
    for (i=1;i<=m;i++)
    {
        fin >> t >> x >> y;
        if (t == 1)
            unite(x,y);
        else
        {
            int rx,ry;
            rx = root(x);
            ry = root (y);
            if (rx == ry)
                fout << "DA" << '\n';
            else
                fout << "NU" << '\n';
        }
    }
    return 0;
}