Cod sursa(job #2538951)

Utilizator AlexTacuTacu Alexandru AlexTacu Data 5 februarie 2020 13:45:49
Problema Paduri de multimi disjuncte Scor 30
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.3 kb
#include <bits/stdc++.h>

using namespace std;

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

struct art
{
    int x,h;
};

art v[505];
int n,m;
int a,b,c;
int r;

void compresie(int a)
{
    if(v[a].x!=a)
        compresie(v[a].x);
    else
    {
        r=a;
        return ;
    }
    v[a].x=r;
    v[a].h=2;
}

int main()
{
    in>>n>>m;
    for(int i=1; i<=n; i++)
    {
        v[i].x=i;
        v[i].h=1;
    }
    while(m)
    {
        in>>a>>b>>c;
        compresie(b);
        compresie(c);
        if(a==1)
        {
            if(v[b].x!=c and v[c].x!=b)
            {

                if(v[b].h<=v[c].h)
                {
                    v[v[b].x].x=c;
                    if(v[b].h!=1)
                        v[v[b].x].h+=v[c].h;
                    v[b].h+=v[c].h;
                }
                else
                {
                    v[v[c].x].x=b;
                    if(v[c].h!=1)
                        v[v[c].x].h+=v[b].h;
                    v[c].h+=v[b].h;
                }
            }
        }
        else
        {
            int z=v[b].x,zz=v[c].x;
            if(z==zz)
                out<<"DA \n";
            else
                out<<"NU \n";
        }
        m--;
    }
    return 0;
}