Cod sursa(job #1820313)

Utilizator SlevySlevoaca Stefan-Gabriel Slevy Data 1 decembrie 2016 16:13:02
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <iostream>
#include <fstream>
#define NMAX 100001

using namespace std;

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

int n, m;
int father[NMAX], height[NMAX];

int det_father(int x)
{
    int r = x, y;
    while (r != father[r])
        r = father[r];
    while (x != father[x])
    {
        y = father[x];
        father[x] = r;
        x = y;
    }
    return r;
}

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

int main()
{
    in >> n >> m;
    int x, y, op, f1, f2;
    for (int i = 1; i <= n; i++)
    {
        father[i] = i;
        height[i] = 1;
    }
    for (int i = 1; i <= m; i++)
    {
        in >> op >> x >> y;
        if (op == 1)
            unite(det_father(x), det_father(y));
        else
        {
            if (x == y)
            {
                out << "DA\n";
                continue;
            }
            f1 = det_father(x);
            f2 = det_father(y);
            out << ((f1 == f2) ? "DA\n" : "NU\n");
        }
    }
    in.close();
    out.close();
    return 0;
}