Cod sursa(job #1236528)

Utilizator Vally77FMI Calinescu Valentin Gelu Vally77 Data 2 octombrie 2014 01:58:41
Problema Paduri de multimi disjuncte Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.22 kb
#include <fstream>
#include <stack>
using namespace std;
ifstream ka("disjoint.in");
ofstream ki("disjoint.out");

const int N_MAX = 100000;

int rad[N_MAX + 1];
int height[N_MAX + 1];

int n, m;

int radacina(int t)
{
    stack <int> stiva;
    while(rad[t] != t)
    {
        stiva.push(t);
        t = rad[t];
    }
    while(!stiva.empty())
    {
        rad[stiva.top()] = t;
        stiva.pop();
    }
    return t;
}

int main()
{
    ka >> n >> m;
    int c, x, y;
    for(int i = 1; i <= n; i++)
        rad[i] = i;
    for(int i = 1; i <= m; i++)
    {
        ka >> c >> x >> y;
        if(c == 1)
        {
            int x_root = radacina(x);
            int y_root = radacina(y);
            if(height[y_root] > height[x_root])
            {
                rad[x_root] = y_root;
                height[y_root] = max(height[y_root], height[x_root] + 1);
            }
            else
            {
                rad[y_root] = x_root;
                height[x_root] = max(height[x_root], height[y_root] + 1);
            }
        }
        else
        {
            if(radacina(x) == radacina(y))
                ki << "DA";
            else
                ki << "NU";
            ki << '\n';
        }
    }
    return 0;
}