Cod sursa(job #1024207)

Utilizator dumitrualexAlex Dumitru dumitrualex Data 8 noiembrie 2013 13:53:58
Problema Paduri de multimi disjuncte Scor 40
Compilator cpp Status done
Runda Arhiva educationala Marime 1.08 kb
#include <fstream>
#define nmax 10000+5
#define FOR(i, a, b) for(int i = (a); i <= (b); i++)
using namespace std;

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

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

int radacina(int x)
{
    int r = x, t;
    while (r != tata[r])
        r = tata[r];
    while (x != tata[x])
    {
        t = tata[x];
        tata[x] = r;
        x = t;
    }
    return r;
}
int main()
{
    int op, x, y, sx, sy;
    fin >> n >> m;
    FOR(k, 1, n)
        tata[k] = k;
    FOR(k, 1, m)
    {
        fin >> op >> x >> y;
        sx = radacina(x);
        sy = radacina(y);
        if (op == 1)
        {
            if (h[sx] < h[sy])
                tata[sx] = sy;
            else if (h[sx] > h[sy])
                tata[sy] = sx;
            else
            {
                tata[sx] = sy;
                h[sx]++;
            }
        }
        else
        {
            if (sx == sy)
                fout << "DA\n";
            else
                fout << "NU\n";
        }
    }
    return 0;
}