Cod sursa(job #2691809)

Utilizator VladAlexandruAnghelache Vlad VladAlexandru Data 30 decembrie 2020 04:07:47
Problema Paduri de multimi disjuncte Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.96 kb
#include <bits/stdc++.h>

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

int tata[100001], h[100001];

int Reprezentant(int x)
{
    int rez = x;
    while(tata[rez]!=rez)
    {
        rez=tata[rez];
    }

    while(tata[x]!=x)
    {
        int aux = tata[x];
        tata[x]= rez;
        x=aux;
    }

    return rez;
}

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

int main()
{
    int n,m;
    fin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        tata[i]=1;
    }
    while(m--)
    {
        int op,x,y;
        if(op==1)
        {
            if(Reprezentant(x)==Reprezentant(y))
                fout<<"DA";
            else fout<<"NU";
        }
        else{
            Reuniune(Reprezentant(x),Reprezentant(y));
        }
        fout<<"\n";
    }

    return 0;
}