Cod sursa(job #2751303)

Utilizator codrut86Coculescu Ioan-Codrut codrut86 Data 14 mai 2021 18:51:56
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.82 kb
#include <fstream>
using namespace std;

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

const int N = 1e5 + 1;
int t[N], h[N], n, m;

int radacina(int x)
{
    if(t[x] == 0) return x;
    return radacina(t[x]);
}

bool verif(int x, int y)
{
    return (radacina(x) == radacina(y));
}

void legare(int x, int y)
{
    int rx = radacina(x), ry = radacina(y);
    if(h[rx] < h[ry])
        t[rx] = ry;
    else if (h[rx] > h[ry])
        t[ry] = rx;
    else
        t[ry] = rx, h[rx]++;
}

int main()
{
    in >> n >> m;

    for(int i = 0; i < m; i++)
    {
        int tip, x, y;
        in >> tip >> x >> y;

        if(tip == 1) legare(x, y);
        else
        {
            if(verif(x, y)) out << "DA\n";
            else out << "NU\n";
        }
    }
    return 0;
}