Cod sursa(job #1212056)

Utilizator daniel.amarieiDaniel Amariei daniel.amariei Data 23 iulie 2014 18:41:08
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.23 kb
#include <fstream>
using namespace std;

#define SIZE 100001

ifstream ifs("disjoint.in");
ofstream ofs("disjoint.out");

int DS[SIZE], TS[SIZE];

void init(int n)
{
    for (int i = 1; i <= n; ++i)
    {
        DS[i] = i;
    }

    for (int i = 1; i <= n; ++i)
    {
        TS[i] = 1;
    }
}

int parent(int x)
{
    int it = x;
    while (DS[it] != it)
    {
        it = DS[it];
    }
    
    DS[x] = it;
    
    return it;
}

bool find_disjoint_set(int x, int y)
{
    int px = parent(x);
    int py = parent(y);

    return (px == py);
}

void union_disjoint_set(int x, int y)
{
    if (find_disjoint_set(x, y)) return;

    int px = parent(x);
    int py = parent(y);
    
    if (TS[px] > TS[py])
    {
        DS[py] = px;
        TS[py] += TS[px]; 
    }
    else
    {
        DS[px] = py;
        TS[px] += TS[py];
    }
}

int main()
{
    int n, m;

    ifs >> n >> m;
    
    init(n);
    
    for (int i = 0; i < m; ++i)     
    {
        int op, x, y;
        ifs >> op >> x >> y;
        
        if (op == 1)
        {
            union_disjoint_set(x, y);
        }
        else if (op == 2)
        {
            bool res = find_disjoint_set(x, y);
            ofs << (res ? "DA" : "NU") << "\n";
        }
    }

    return 0;
}