Cod sursa(job #2149557)

Utilizator strutu_iStrutu Ilinca Ioana strutu_i Data 2 martie 2018 18:52:37
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.82 kb
#include <fstream>

using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int h[100005],t[100005],n,m,i,j,x,y,c;
int findset(int x)
{
    while(t[x]!=x)
        x=t[x];
    return x;
}
int unionset(int x, int y)
{
    if(h[x]==h[y])
    {
        h[x]++;
        t[y]=x;
    }
    else
    {
        if(h[x]>h[y])
            t[y]=x;
        else
            t[x]=y;
    }
}
int main()
{
    fin>>n>>m;
    for(i=1;i<=n;i++)
    {
        t[i]=i;h[i]=1;
    }
    for(j=1;j<=m;j++)
    {
        fin>>c>>x>>y;
        if(c==1)
        {
            unionset(t[x],t[y]);
        }
        else
        {
            if(findset(x)==findset(y))
                fout<<"DA"<<"\n";
            else
                fout<<"NU"<<"\n";
        }
    }
    return 0;
}