Cod sursa(job #1612616)

Utilizator BaconDroidAndrei Katona BaconDroid Data 24 februarie 2016 22:41:15
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.78 kb
#include <iostream>
#include <fstream>
#define max 100001
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");

int m,n,v[max],r[max],i,c,o,a,b;

int FIND(int x)
{
    if(v[x] == x)
        return x;
    return FIND(v[x]);
}

void UNION(int x, int y)
{
    int tx,ty;
    tx = FIND(x);
    ty = FIND(y);
    if(r[tx] < r[ty])
        v[tx] = ty;
    else if(r[tx] > r[ty])
        v[ty] = tx;
    else
    {
        v[ty] = tx;
        r[tx]++;
    }
}

int main()
{
    f>>n>>m;
    for(i=1; i<=n; i++)
        v[i] = i;
    while(f>>o>>a>>b)
        if(o == 1)
            UNION(a,b);
        else
            if(FIND(a) == FIND(b))
                g << "DA\n";
            else
                g << "NU\n";
    return 0;
}