Cod sursa(job #1886282)

Utilizator LaurIleIle Laurentiu Daniel LaurIle Data 20 februarie 2017 19:59:17
Problema Paduri de multimi disjuncte Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include <iostream>
#include <fstream>
#define nmax 100000+5
using namespace std;

int n, m, cod;
int tata[nmax], h[nmax];

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

int fnd(int x)
{
    int r=x;
    while(tata[r]) r=tata[r];
    int y=x, aux;
    while(y!=r)
    {
        aux=tata[y]; tata[y]=r; y=aux;
    }
    return r;
}

void uni(int x, int y)
{
    if(h[x] > h[y])
        tata[y] = x;
    else
    {
        tata[x] = y;
        if(h[x] == h[y])
            h[y]++;
    }
}

int main()
{
    f >> n >> m;
    for(int i=0, x, y; i<m; ++i)
    {
        f >> cod >> x >> y;
        if(cod == 1)
            uni(x ,y);
        else
        {
            if(fnd(x) == fnd(y))
                g << "DA" << '\n';
            else
                g << "NU" << '\n';
        }
    }
    f.close();
    g.close();
    return 0;
}