Cod sursa(job #2193012)

Utilizator Narvik13Razvan Roatis Narvik13 Data 8 aprilie 2018 12:58:25
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <fstream>
#include <iostream>
#define NMAX 100002

using namespace std;

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

int n,m;
int grad[NMAX], tata[NMAX];

int init()
{
    for(int i = 1; i <= n; ++i)
    {
        tata[i] = i;
        grad[i] = 1;
    }
}

int where_is_it(int nod)
{
    int aux = nod;

    while(aux != tata[aux])
    {
        aux = tata[aux];
    }

    int aux2;

    while(nod != tata[nod])
    {
        int aux2 = tata[nod];
        tata[nod] = aux;
        nod = aux2;
    }

    return aux;
}

void unite(int nod1, int nod2)
{
    if(grad[nod1] > grad[nod2])
        tata[nod2] = nod1;
    else
        tata[nod1] = nod2;
    if(grad[nod1] == grad[nod2])
        ++ grad[nod2];
}

int main()
{
    f >> n >> m;
    init();
    int a,b,c;
    for(int i = 1; i <= m; ++i)
    {
        f >> c >> a >> b;
        if(c == 1)
            unite(where_is_it(a),where_is_it(b));
        else
        {
            //cout << where_is_it(a) << " " << where_is_it(b) << "\n";
            if(where_is_it(a) == where_is_it(b))
                o << "DA\n";
            else
                o << "NU\n";
        }
    }
    return 0;
}