Cod sursa(job #2722795)

Utilizator CRazvaN6Cutuliga Razvan CRazvaN6 Data 13 martie 2021 12:11:37
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.95 kb
#include <bits/stdc++.h>
using namespace std;

ifstream f("disjoint.in");
ofstream g("disjoint.out");
int n, m;
int tata[100100], h[100100];
int radacina(int nod)
{
    while(tata[nod] != 0) nod = tata[nod];
    return nod;
}
void unire(int nod1, int nod2)
{
    int rad1 = radacina(nod1);
    int rad2 = radacina(nod2);
    if(h[rad1] < h[rad2]) tata[rad1] = rad2;
    else if( h[rad1] > h[rad2]) tata[rad2] = rad1;
    else tata[rad1] = rad2, h[rad2] ++;
}
int query(int nod1, int nod2)
{
    int r1 = radacina(nod1);
    int r2 = radacina(nod2);
    if(r1 == r2) return 1;
    return 0;
}
int main()
{
    f >> n >> m;
    for(int i = 1; i <= m ;++i)
    {
        int c, x, y;
        f >> c >> x >> y;
        if(c == 1)
            unire(x,y);
        else
        {
            int ans = query(x,y);
            if(ans == 1) g << "DA" << '\n';
                else g << "NU" << '\n';
        }
    }
    return 0;
}