Cod sursa(job #2797232)

Utilizator vivifromloonaAlexandru Alexandru vivifromloona Data 9 noiembrie 2021 16:36:03
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <fstream>
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
const int nmax=100001;
int t[nmax],h[nmax];

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,ok;
    fin>>n>>m;
    for(i=1;i<=n;i++)
    {
        t[i]=i;
        h[i]=1;
    }
    for(i=1;i<=m;i++)
    {
        fin>>ok>>x>>y;
        if(ok==1)
        {
            tx=findSet(x);
            ty=findSet(y);
            if(tx!=ty)
                UnionSet(tx,ty);
        }
        if(ok==2)
        {
            tx=findSet(x);
            ty=findSet(y);
            if(tx!=ty)
                fout<<"NU"<<endl;
            else
                fout<<"DA"<<endl;;
        }
    }
    return 0;
}