Cod sursa(job #3273354)

Utilizator Ayan__bAyan Bozesan Ayan__b Data 1 februarie 2025 19:34:33
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.03 kb
#include <iostream>
#include <fstream>

using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");

struct nod
{
    nod* father;
    int rang;

};
nod* papi(nod* a)
{
    if(a->father==nullptr)
        return a;
    return papi(a->father);
}
void join(nod* a, nod* b)
{
    a=papi(a);
    b=papi(b);
    if(a->rang<b->rang)
        a->father=b;
    else if(a->rang>b->rang)
        b->father=a;
    else
    {
        a->father=b;
        b->rang++;
    }
}
int main()
{
    int n;
    int m;
    f>>n>>m;
    short int cod;

    nod* v[n];
    for(int i=1;i<n+1;i++)
    {
        v[i]=new nod;
        v[i]->father=nullptr;
        v[i]->rang=1;
    }
    for(int i=0;i<m;i++)
    {
        f>>cod;
        int x,y;
        f>>x>>y;
        if(cod==1)
        {
            join(v[x],v[y]);
        }
        if(cod==2)
        {
            if(papi(v[x])==papi(v[y]))
                g<<"DA\n";
            else
                g<<"NU\n";
        }
    }
    return 0;
}