Cod sursa(job #949167)

Utilizator BitOneSAlexandru BitOne Data 12 mai 2013 18:31:10
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.94 kb
#include <cstdlib>
#include <fstream>

using namespace std;

const int NMAX = 100011;

int r[NMAX], f[NMAX];

int find(int x)
{
    int y, z;

    for(y = f[x]; y != f[y]; y = f[y]);
    while(x != f[x])
    {
        z = f[x];
        f[x] = y;
        x = z;
    }
    return y;
}
inline void Union(int x, int y)
{
    int fx = find(x), fy = find(y);

    if(fx == fy) return;
    if(r[fx] < r[fy]) f[fx] = fy;
    else if(r[fy] > r[fx]) f[fy] = fx;
    else {
            f[fx] = fy;
            ++r[fy];
         }
}

int main()
{
    int N, M, x, y, op, i;
    ifstream in("disjoint.in");
    ofstream out("disjoint.out");

    in >> N >> M;
    for(i = 1; i <= N; ++i)
    {
        f[i] = i;
        r[i] = 1;
    }
    while(M--)
    {
        in >> op >> x >> y;
        if(2 == op) out << (find(x) == find(y) ? "DA" : "NU") << '\n';
        else Union(x, y);
    }

    return EXIT_SUCCESS;
}