Cod sursa(job #2842906)

Utilizator RobertAcAcatrinei Robert-Marian RobertAc Data 1 februarie 2022 18:16:08
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <bits/stdc++.h>
#define nmax 100005
using namespace std;

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

struct nod
{
    int h;
    nod *father;
    int val;
    nod(int h)
    {
        val=0;
        this->h=h+1;
        father=nullptr;
    }
    nod(int h,int i)
    {
        val=i;
        h=1;
        father=new nod(h+1);
    }
    nod* getgrandfather()
    {
        if(father==nullptr)return this;
        else return father->getgrandfather();
    }
    void leaga(nod *newfather)
    {
        if(father==nullptr)return;
        else
        {
            father->leaga(newfather);
            father=newfather;
        }
    }
};

nod *noduri[nmax];

int main()
{
    int n,m;
    in>>n>>m;
    for(int i=1;i<=n;i++)
    {
        noduri[i]=new nod(0,i);
    }
    for(int i=0;i<m;i++)
    {
        int t,x,y;
        in>>t>>x>>y;
        if(t==2)
        {
            nod *a=noduri[x]->getgrandfather();
            nod *b=noduri[y]->getgrandfather();
            if(a==b)out<<"DA\n";
            else out<<"NU\n";
            noduri[x]->leaga(a);
            noduri[y]->leaga(b);
        }
        else
        {
            nod *a=noduri[x]->getgrandfather();
            nod *b=noduri[y]->getgrandfather();
            if((a->h)>(b->h))b->father=a;
            else a->father=b;
            if((a->h)==(b->h))b->h++;
        }
    }
}