Cod sursa(job #2696477)

Utilizator toma_ariciuAriciu Toma toma_ariciu Data 15 ianuarie 2021 23:46:27
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <iostream>
#include <fstream>

using namespace std;

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

int nr_operatii, n;
int root[100005], depth[100005];

void join(int n, int m)
{
    if(depth[n] > depth[m])
    {
        root[m]=n;
    }
    if(depth[n] < depth[m])
    {
        root[n]=m;
    }
    if(depth[n] == depth[m])
    {
        root[m]=n;
        depth[n]++;
    }
}

void check(int n, int m)
{
    if(n==m)
        fout<<"DA";
    else
        fout<<"NU";
    fout<<'\n';
}
int findRoot(int n)
{
    if(root[n]==0)
        return n;
    else
        return findRoot(root[n]);
}

void solve()
{
    fin>>n>>nr_operatii;
    for(int i=1; i<=nr_operatii; i++)
    {
        int cod, x, y;
        fin>>cod>>x>>y;
        if(cod==1)
        {
            int rx, ry;
            rx=findRoot(x);
            ry=findRoot(y);
            join(rx, ry);
        }
        if(cod==2)
        {
            int rx, ry;
            rx=findRoot(x);
            ry=findRoot(y);
            check(rx, ry);
        }
    }
}

int main()
{
    solve();
    return 0;
}