Cod sursa(job #1413696)

Utilizator teo.serbanescuTeo Serbanescu teo.serbanescu Data 2 aprilie 2015 01:01:22
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include <fstream>

using namespace std;

fstream f("disjoint.in", ios::in);
fstream g("disjoint.out", ios::out);

const int nmax = 100005;
int a[nmax], r[nmax], n, m, q, x, y, i;

int query(int x)
{
    int k, aux;
    k = x;
    while (k != a[k])
    {
        k = a[k];
    }
    while (x != a[x])
    {
        aux = a[x];
        a[x] = k;
        x = aux;
    }
    return k;
}

void connect(int x, int y)
{
    int qx, qy;
    qx = query(x); qy = query(y);
    if (r[qx] > r[qy]) a[qy] = qx;
                else a[qx] = qy;
    if (r[qx] == r[qy]) r[qy]++;
}

int main()
{
    f >> n >> m;
    for (i = 1; i <= n; i++)
    {
        a[i] = i;
        r[i] = 1;
    }
    for (i = 1; i <= m; i++)
    {
        f >> q >> x >> y;
        if (q == 1)
        {
            connect(x, y);
        }
        if (q == 2)
        {
            if (query(x) == query(y)) g << "DA\n";
                                else g << "NU\n";
        }
    }
    return 0;
}