Cod sursa(job #1593095)

Utilizator sulzandreiandrei sulzandrei Data 8 februarie 2016 11:59:09
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");
int p[10000],rang[100000];
int GasesteMultime(int x)
{
    if ( p[x] == x)
        return x;
    p[x] = GasesteMultime(p[x]);
};
int FormeazaMultime(int x)
{
    rang[x] = 0;
    p[x] = x;
};
void Uneste(int x, int y)
{
    if (rang[x] > rang[y])
        p[y] = x,rang[x]++;
    else
        p[x] = y,rang[y]++;
}
void Reuneste(int x, int y)
{
    Uneste(GasesteMultime(x),GasesteMultime(y));
}

int main()
{
    int n,m,op,x,y;
    in >> n >> m;
    for(int i = 1 ; i <= n ; i ++)
        FormeazaMultime(i);
    while(m--)
    {
        in >> op >> x >> y;
        switch(op)
        {
            case 1: Reuneste(x,y); break;
            case 2: if (GasesteMultime(x) == GasesteMultime(y))
                        out<<"DA\n";
                    else
                        out<<"NU\n";
                    break;
        }
    }
    return 0;
}