Cod sursa(job #2496812)

Utilizator XXMihaiXX969Gherghinescu Mihai Andrei XXMihaiXX969 Data 21 noiembrie 2019 18:04:34
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.23 kb
#include <iostream>
#include <fstream>

using namespace std;

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

const int DIM =1e5 + 7;

int p[DIM];

int findp(int x)
{
    if(p[x] < 0)
        return x;
    else
    return findp(p[x]);
}

void unionp(int x, int y)
{
    int a = findp(x);
    int b = findp(y);

    if(p[a] <= p[b])
    {
        p[a] = p[a] + p[b];
        p[b] = a;
    }
    else
    {
        p[b] = p[b] + p[a];
        p[a] = b;
    }
}
int main()
{


    int n,q;

    in >> n >> q;
   /* daca p[i] este negativ atunci el este tata iar -p[i] rep nr de noduri din arbore, arbori mereu se leaga cel cu mai putine elemente de cel cu mai multe elemente */
       for(int i = 1; i <= n; i++)
        p[i] = -1;

    while(q--)
    {
        int x, y, t;

        in >> t >> x >> y;

        if(t == 1)
        {
        int s1 = findp(x);
        int s2 = findp(y);
        if(s1 != s2)
            unionp(s1,s2);
        }
        else
        {
            int s1 = findp(x);
            int s2 = findp(y);

            if(s1 == s2)
                out <<"DA" <<"\n";
            else
                out <<"NU" <<"\n";
        }
    }
    return 0;
}