Cod sursa(job #2289144)

Utilizator MarianConstantinMarian Constantin MarianConstantin Data 24 noiembrie 2018 11:35:39
Problema Paduri de multimi disjuncte Scor 80
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <iostream>
#include <fstream>
#define NMAX 100010

using namespace std;

int father[NMAX], height[NMAX];

int findFather(int k)
{
    int f, aux;
    for (f=k; f!=father[f]; f=father[f])
    {}
    for (; father[k]!=k;)
    {
        aux = father[k];
        father[k] = f;
        k = aux;
    }
    return f;
}

void unite(int x, int y)
{
    if (height[x] <  height[y])
        father[x] = y;
    else
        father[y] = x;
    if (height[x] == height[y])
        height[y]++;
}

int main()
{
    ifstream fin("disjoint.in");
    ofstream fout("disjoint.out");
    int n, m, k, x, y, value;
    fin >> n >> m;
    for (int i=1; i<=n; i++)
    {
        father[i] = i;
        height[i] = 1;
    }
    for (int i=1; i<=m; i++)
    {
        fin >> k >> x >> y;
        if (k == 1)
        {
            if (findFather(x) == findFather(y))
            {
                return 0;
            }
            unite(x, y);
        }
        else
        {
            if (findFather(x) == findFather(y))
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }
    return 0;
}