Cod sursa(job #1968426)

Utilizator TibixbAndrei Tiberiu Tibixb Data 17 aprilie 2017 18:04:20
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include<fstream>
#define NMAX 100000
using namespace std;
int n, m, op, x, y, rx, ry;
int up;
int t[NMAX + 5];
ifstream _cin("disjoint.in");
ofstream _cout("disjoint.out");

int rad(int nod)
{
    while(t[nod] > 0)
    {
        nod = t[nod];
    }
    return nod;
}

void compresie(int nod, int rad)
{
    while(t[nod] > 0)
    {
        up = t[nod];
        t[nod] = rad;
        nod = up;
    }
}

void unite(int x, int y)
{
    rx = rad(x);
    ry = rad(y);
    if(rx != ry)
    {
        if(t[rx] > t[ry])
        {
            swap(rx, ry);
            swap(x, y);
        }
        t[rx] += t[ry];
        t[ry] = rx;
        compresie(y, rx);
    }
}

void init()
{
    for(int i = 1; i <= NMAX; i++)
    {
        t[i] = -1;
    }
}

int main()
{
    init();

    _cin >> n >> m;
    while(m--)
    {
        _cin >> op >> x >> y;
        if(op == 1)
        {
            unite(x, y);
        }else
        {
            rx = rad(x);
            ry = rad(y);
            if(rx == ry)
            {
                _cout << "DA\n";
            }else
            {
                _cout << "NU\n";
            }
        }
    }
    return 0;
}