Cod sursa(job #2090858)

Utilizator AndreiMaximIonutMaxim Andrei AndreiMaximIonut Data 18 decembrie 2017 19:54:02
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.88 kb
#include <fstream>

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

short h[100001];
int tata[100001];
char op;
int N, M, x, y;

int Find(int x)
{
    int r = x;

    while(tata[r]) r = tata[r];

    int y = x, aux;

    while(y != r)
    {
        aux = tata[y];
        tata[y] = r;
        y = aux;
    }

    return r;
}

void Union(int c1, int c2)
{
    if(h[c1] > h[c2]) tata[c2] = c1;

    else
    {
        tata[c1] = c2;

        if(h[c1] == h[c2]) h[c2]++;
    }
}

int main()
{
    int c1, c2;

    fin>>N>>M;

    for(; M; --M)
    {
        fin>>op;
        fin>>x>>y;

        c1 = Find(x);
        c2 = Find(y);

        if(op == '1')  Union(c1, c2);

        else
        {
            if(c1 != c2) fout<<"NU"<<'\n';
            else fout<<"DA"<<'\n';
        }
    }
    return 0;
}