Cod sursa(job #2001462)

Utilizator Coroian_DavidCoroian David Coroian_David Data 16 iulie 2017 19:01:50
Problema Paduri de multimi disjuncte Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include <cstdio>

using namespace std;

FILE *f, *g;

int n, m;

int h[100009];
int comp[100009];

int getComp(int a)
{
    if(comp[a] == a)
        return a;

    comp[a] = getComp(comp[a]);

    return comp[a];
}

void unity(int a, int b)
{
    if(h[a] > h[b])
    {
        comp[b] = a;

        return;
    }

    if(h[a] == h[b])
    {
        h[a] ++;
        comp[b] = a;

        return;
    }

    if(h[a] < h[b])
    {
        comp[a] = b;

        return;
    }
}

void ansQues()
{
    f = fopen("disjoint.in", "r");
    g = fopen("disjoint.out", "w");

    fscanf(f, "%d%d", &n, &m);

    int i;
    for(i = 1; i <= n; i ++)
        h[i] = 1, comp[i] = i;

    int a, b, c;
    while(m > 0)
    {
        m --;

        fscanf(f, "%d%d%d", &c, &a, &b);

        //printf("--%d  %d %d   %d %d\n", c, a, b,getComp(a), getComp(b));

        if(c == 2)
            fprintf(g, "%s\n", getComp(a) == getComp(b) ? "DA" : "NU");

        else
            unity(getComp(a), getComp(b));


        //printf("++%d  %d %d   %d %d\n", c, a, b,getComp(a), getComp(b));
    }

    fclose(f);
    fclose(g);
}

int main()
{
    ansQues();

    return 0;
}