Cod sursa(job #1194619)

Utilizator projectanduFMI Stanescu Andrei Alexandru projectandu Data 4 iunie 2014 11:56:35
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.78 kb
#include <iostream>
#include <fstream>

using namespace std;
#define dim 100001

int adancime[dim], tata[dim];


struct bananier
{
    int x, y;
};

//cu comprimare drum
int gaseste(int x)
{
    if(tata[x] != tata[tata[x]])
        tata[x] = gaseste(tata[x]);
    return tata[x];

    /*
    SAU asa, de vazut care e mai rapida :
    while(x  !=  tata[x])
    {
        tata[x] = tata[tata[x]];
        x = tata[x];
    }
    */
}

bool uneste(int x, int y)
{
    int x_aux = gaseste(x), y_aux = gaseste(y), aux;
    if(x_aux  ==  y_aux)
        return false;

    //fac ca x sa aiba adancimea mai mica
    if(adancime[x_aux]  >  adancime[y_aux])
        {
            aux = x_aux;
            x_aux = y_aux;
            y_aux = aux;
        }
    //daca au adancimi egale, atunci adancimea arborelui ce se formeaza creste cu 1
   if(adancime[x_aux]  ==  adancime[y_aux])
        ++adancime[y_aux];
   tata[x_aux] = y_aux;
   return true;
}


//de testat cu datele din paduri disjuncte de pe infoarena
int main()
{
    //bananier b[dim];
    ifstream f("disjoint.in");
    ofstream g("disjoint.out");
    //din cate mai imi amintesc, se citeau n nr si m perechi ce deveneau vecini
    int n, nr_perechi, optiune, x, y, i;
    f >> n >> nr_perechi;
    for(i = 0; i < n; ++i)
        {
            tata[i] = i;
            adancime[i] = 1;
        }
    for(i = 0; i < nr_perechi; ++i)
    {
        f >> optiune >> x >> y;
        if(optiune ==  2)
            {
                if(gaseste(x)  ==  gaseste(y))
                    g << "DA\n";
                else
                    g << "NU\n";
            }
            else
                {
                    uneste(gaseste(x), gaseste(y));
                }
    }
    return 0;
}