Cod sursa(job #1593100)

Utilizator sulzandreiandrei sulzandrei Data 8 februarie 2016 12:01:53
Problema Paduri de multimi disjuncte Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 kb
#include <iostream>
#include <fstream>
using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");
int p[100000],rang[100000];
int GasesteMultime(int x)
{
    if ( p[x] != x)
        p[x] = GasesteMultime(p[x]);
    return 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;
    else
        p[x] = y;
    if( rang[x] == rang[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;
}