Cod sursa(job #2797219)

Utilizator ndg_gdnNan Diana ndg_gdn Data 9 noiembrie 2021 16:31:58
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.97 kb
#include <fstream>

using namespace std;

ifstream fin("disjoint.in");
ofstream fout("disjoint.out");

int t[100001], h[100001];

int findSet(int x)
{
    while(t[x]!=x)
        x=t[x];
    return x;
}

void unionSet(int x, int y)
{
    if(h[x]>h[y])
        t[y]=x;
    else
        if(h[y]>h[x])
        t[x]=y;
    else
    {
        t[y]=x;
        ++h[x];
    }
}

int main()
{
    int n,i,m,x,y,tx,ty,op;
    fin>>n>>m;

    for(i=1;i<=n;++i)
    {
        t[i]=i;
        h[i]=1;
    }

    for(i=1;i<=m;++i)
    {
        fin>>op;
        fin>>x>>y;
        if(op==1)
        {
            tx=findSet(x);
            ty=findSet(y);
            if(tx!=ty)
                unionSet(tx,ty);
        }
        if(op==2)
        {
            tx=findSet(x);
            ty=findSet(y);
            if(tx==ty)
                fout<<"DA"<<"\n";
            else
                fout<<"NU"<<"\n";
        }
    }

    return 0;
}