Cod sursa(job #1640517)

Utilizator Mr.DoomRaul Ignatus Mr.Doom Data 8 martie 2016 18:06:56
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.02 kb
#include <fstream>
using namespace std;

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

int p[100001], h[100001];
int n, m;

void Union(int x, int y);
int Find(int x);

int main()
{
    int n, m;
    is >> n >> m;
    int op, x, y;
    for ( int i = 1; i <= n; ++i )
        p[i] = i, h[i] = 1;
    for ( int i = 1; i <= m; ++i )
    {
        is >> op >> x >> y;
        switch ( op )
        {
            case 1 :
                Union(Find(x), Find(y));
                break;
            case 2 :
                if ( Find(x) == Find(y) )
                    os << "DA" << '\n';
                else
                    os << "NU" << '\n';
                break;
        }
    }
    is.close();
    os.close();
    return 0;
}

void Union(int x, int y)
{
    if ( h[x] > h[y] )
        p[y] = x;
    else
    {
        p[x] = y;
        if ( h[x] == h[y] )
            h[y]++;
    }
}

int Find(int x)
{
    if ( x != p[x] )
        p[x] = Find(p[x]);
    return p[x];
}