Cod sursa(job #1857091)

Utilizator raduzxstefanescu radu raduzx Data 25 ianuarie 2017 20:05:52
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.06 kb
#include <fstream>

using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
int v[100003],rg[100003];
int father(int a)
{
    while(v[a])
        a=v[a];
    return a;
}
int n,i,m,x,y,tx,ty,cx,cod;
int main()
{
    f>>n>>m;
    for(i=1;i<=m;i++)
    {
        f>>cod>>x>>y;
        if(cod==2)
        {
            if(father(x)==father(y))
                g<<"DA"<<'\n';
            else
                g<<"NU"<<'\n';
        }
        else
        {
            tx=father(x);
            ty=father(y);
            if(tx!=ty)
            {
                while(x)
                {
                    cx=x;
                    x=v[x];
                    v[x]=tx;
                }
                if(rg[tx]==rg[ty])
                {
                    rg[tx]+=1;
                    v[ty]=tx;
                }
                else
                    if(rg[tx]>rg[ty])
                        v[ty]=tx;
                    else
                        v[tx]=ty;
            }
        }
    }
    return 0;
}