Cod sursa(job #2172147)

Utilizator alex.surdubobAlex Surdu alex.surdubob Data 15 martie 2018 15:16:58
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.09 kb
#include <fstream>
using namespace std;

ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

int n, m;

int tata[100000], niv[100000];

int fnd(int x)
{
    int y = x, r = x;
    while(tata[r] != 0)
    {
        r = tata[r];
    }
    while(tata[y] != 0)
    {
        int z = tata[y];
        tata[y] = r;
        y = z;
    }
    return r;
}

void uni(int x, int y)
{
    int t1 = x, t2 = x;

    if(t1 != t2)
    {
        if(niv[t1] < niv[t2])
        {
            tata[t1] = t2;
        }
        else
        {
            tata[t2] = t1;
        }
        if(niv[t1] == niv[t2]){
            tata[t2] = t1;
            niv[t1]++;
        }
    }
}

int main()
{
    fin >> n >> m;
    for(int i = 1; i <= m; i++)
    {
        short cod;
        int x, y;
        fin >> cod >> x >> y;
        int fx = fnd(x), fy = fnd(y);
        if(cod == 2)
        {
            if(fx == fy)
            {
                fout << "DA\n";
            }
            else{
                fout << "NU\n";
            }
        }
        else
        {
            uni(fx, fy);
        }
    }



    return 0;
}