Cod sursa(job #1235972)

Utilizator hopingsteamMatraguna Mihai-Alexandru hopingsteam Data 30 septembrie 2014 23:33:44
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.09 kb
#include    <fstream>
using namespace std;

const int NMax = 100005;

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

int N, M;
int T[NMax], Height[NMax];

int Root(int x)
{
    int rOOT, aux;
    while(x != T[x])
        x = T[x];
    
    rOOT = x;
    while(x != T[x])
    {
        aux = T[x];
        T[x] = rOOT;
        x = aux;
    }
    return rOOT;
}

void Unite(int x, int y)
{
    if(Height[x] > Height[y])
        T[y] = x;
    else
        T[x] = y;
    
    if(Height[x] == Height[y]) Height[y] += 1; //If there're equal, we just add one more
}

void Read()
{
    int op, x, y;
    fin >> N >> M;
    
    for(int i = 1; i <= N; i++)
    {
        T[i] = i;
        Height[i] = 1;
    }
    
    for(int i = 1; i <= M; i++)
    {
        fin >> op >> x >> y;
        if(op == 1)
           Unite(Root(x),Root(y)); 
        if(op==2)
        {
            if(Root(x)==Root(y))
                fout<<"DA\n";
            else    
                fout<<"NU\n";
        }
    }
}

int main()
{
    Read();
    return 0;
}