Cod sursa(job #2158566)

Utilizator IustinPetrariuIustinian Petrariu IustinPetrariu Data 10 martie 2018 13:56:23
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.86 kb
#include <iostream>
#include <fstream>
#define nmax 100001

using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int t[nmax],h[nmax],rx,ry,z,x,n,m,c,y;
int Find(int x)
{
     int rx=x,z;
     while(t[rx])
        rx=t[rx];
     while(x!=rx)
     {
         z=t[x];
         t[x]=rx;
         x=z;
     }
     return rx;
}
void Union(int rx, int ry)
{
    if(h[rx]==h[ry])
    {
        h[rx]++;
        t[rx]=ry;
    }
    else if(h[rx]<h[ry])
    {
        t[rx]=ry;
    }
    else t[ry]=rx;
}
void solve()
{
    while(m--)
    {
        fin>>c>>x>>y;
        rx=Find(x);
        ry=Find(y);
        if(c==1) Union(rx,ry);
        else
        {
            if(rx==ry) fout<<"DA"<<'\n';
            else fout<<"NU"<<'\n';
        }
    }
}
int main()
{
     fin>>n>>m;

    solve();
    return 0;
}