Cod sursa(job #1490411)

Utilizator AdrianaMAdriana Moisil AdrianaM Data 23 septembrie 2015 14:51:30
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.96 kb
#include <fstream>
#include <vector>
#include <stack>
#include <bitset>
#define INF 0x3f3f3f3f
using namespace std;

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

int n, m;
vector<int> t, h;

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

int main()
{
    is >> n >> m;
    h = t = vector<int>(n + 1);
    for ( int i = 1; i <= n; ++i )
        t[i] = i;
    int x, y, tip;
    while ( m-- )
    {
        is >> tip >> x >> y;
        if ( tip == 1 )
            Union(Find(x), Find(y));
        else
            if ( Find(x) == Find(y) )
                os << "DA\n";
            else
                os << "NU\n";
    }
    is.close();
    os.close();
    return 0;
}

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

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