Cod sursa(job #2766718)

Utilizator CelestinNegraru Celestin Celestin Data 2 august 2021 23:18:15
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <iostream>
#include <fstream>
#define maxi 100000
using namespace std;
ifstream f;
ofstream g;
int n,m,RANG[1+maxi],R[1+maxi];
void INIT()
{
    for(int i=1;i<=n;i++)
        R[i]=i,RANG[i]=1;
    return;
}
int REPREZENTANT(int x)
{
    while(x!=R[x])
        x=R[x];
    return x;
}
void UNIRE(int x,int y)
{
    if(RANG[x]>RANG[y])
    {
        R[y]=x;
    }
    if(RANG[x]<RANG[y])
    {
        R[x]=y;
    }
    if(RANG[x]==RANG[y])
    {
        RANG[x]++;
        R[y]=x;
    }
    return;
}
void READ()
{
    int c,x,y;
    f.open("disjoint.in",ios::in);
    g.open("disjoint.out",ios::out);
    f>>n>>m;
    INIT();
    for(int i=1;i<=m;i++)
    {
        f>>c>>x>>y;
        if(c==1)
        {
           int rx=REPREZENTANT(x);
           int ry=REPREZENTANT(y);
           UNIRE(rx,ry);
        }
        else{
            int rx=REPREZENTANT(x);
            int ry=REPREZENTANT(y);
            if(rx==ry)
                g<<"DA\n";
            else g<<"NU\n";
        }
    }
    f.close();
    g.close();
    return;
}
int main()
{
    READ();
    return 0;
}