Cod sursa(job #1376934)

Utilizator pop_bogdanBogdan Pop pop_bogdan Data 5 martie 2015 19:25:34
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.08 kb
#include <fstream>
using namespace std;

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

#define DIM 100001

int N, M, T[DIM], Rank[DIM], Root[DIM], Type, x, y;

int Find(int x)
{
    int root(x), aux;

    while ( root != T[root] )
        root = T[root];

    while ( x != T[x] )
    {
        aux = x;
        T[x] = root;
        x = T[aux];
    }

    return root;
}

void Union(int x, int y)
{
    if ( Rank[x] > Rank[y] )
        T[y] = x;
    if ( Rank[x] <= Rank[y] )
    {
        T[x] = y;
        Rank[x] += ((int)(Rank[x] == Rank[y]));
    }
}

int main()
{
    is >> N >> M;
    for ( int i = 1; i <= N; ++i )
        T[i] = i;

    for ( int i = 1; i <= M; ++i )
    {
        is >> Type;
        is >> x >> y;
        switch(Type)
        {
            case 2:
                if ( Find(x) == Find(y) )
                    os << "DA\n";
                else
                    os << "NU\n";
                break;
            case 1:
                Union(Find(x),Find(y));
                break;
        }
    }
}