Cod sursa(job #1487700)

Utilizator DenisONIcBanu Denis Andrei DenisONIc Data 17 septembrie 2015 11:55:38
Problema Paduri de multimi disjuncte Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
using namespace std;

ifstream f("disjoint.in");
ofstream g("disjoint.out");

long t,x,y,n,m,i,j;
struct grupe
{
    long nr,ant;
}gr[100004];

long rad(long nod,long &lg)
{
    if (gr[nod].ant!=-1)
    {
        nod=gr[nod].ant;
        lg++;
        rad(nod, lg);
    }
    else
        return nod;
}

void uneste(long x,long y)
{
    long lgx=1,lgy=1,rx,ry;
    rx=rad(x,lgx);
    ry=rad(y,lgy);
    if (lgx<=lgy)
    {
        gr[rx].ant=ry;
        gr[rx].nr=gr[ry].nr;
    }
    else
    {
        gr[ry].ant=rx;
        gr[ry].nr=gr[rx].nr;
    }
}

long qu(long x,long y)
{
    long rx,ry,lgx,lgy;
    rx=rad(x,lgx);
    ry=rad(y,lgy);
    if(gr[rx].nr==gr[ry].nr)
        return 1;
    return 0;
}

int main()
{
    f>>n>>m;
    for (i=1;i<=n;i++)
    {
        gr[i].nr=i;
        gr[i].ant=-1;
    }
    for (i=1;i<=m;i++)
    {
        f>>t>>x>>y;
        if (t==1)
        {
            if (qu(x,y)==0)
            uneste(x,y);
        }
        else
        {
            if (qu(x,y)==1)
                g<<"DA\n";
            else
                g<<"NU\n";
        }
    }

    return 0;
}