Cod sursa(job #1894758)

Utilizator NoSwearFlorea Marian NoSwear Data 27 februarie 2017 14:42:00
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include<fstream>
#define NMAX 100005
using namespace std;
int n, m, op, x, y, rx, ry, up;
int t[NMAX];
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 root)
{
    while(nod != root)
    {
        up = t[nod];
        t[nod] = root;
        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);
        }
        t[rx] += t[ry];
        t[ry] = rx;
        compresie(y, rx);
    }
}
int main()
{
    cin >> n >>  m;
    for(int i = 1; i <= m; i++)
    {
        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;
}