Cod sursa(job #2252398)

Utilizator 24601Dan Ban 24601 Data 2 octombrie 2018 18:55:47
Problema Paduri de multimi disjuncte Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.84 kb
#include <stdio.h>
#include <stdlib.h>

#define NMAX 100000

struct set {
    struct obj *head;
    size_t length;
};

struct obj {
    struct set *s;
    struct obj *next;
    int x;
};

static struct obj *elem_to_obj[NMAX+1];

/*static struct obj obj_pool[NMAX+1];*/
/*static struct set set_pool[NMAX+1];*/
/*static size_t obj_pool_next, set_pool_next;*/

static void make_set(int x)
{
    /*struct set *new_set = &set_pool[set_pool_next++];*/
    /*struct obj *new_obj = &obj_pool[obj_pool_next++];*/
    struct set *new_set = malloc(sizeof (struct set));
    struct obj *new_obj = malloc(sizeof (struct obj));

    new_obj->s = new_set;
    new_obj->next = NULL;
    new_obj->x = x;

    new_set->head = new_obj;
    new_set->length = 1;

    elem_to_obj[x] = new_obj;
}

static struct obj *find_set(int x)
{
    return elem_to_obj[x]->s->head;
}

static void union_op(int x, int y)
{
    struct set *s_x = elem_to_obj[x]->s;
    struct set *s_y = elem_to_obj[y]->s;
    struct set *min_s, *max_s;
    struct obj *o, *aux;

    if (s_x->length < s_y->length) {
        min_s = s_x;
        max_s = s_y;
    } else {
        min_s = s_y;
        max_s = s_x;
    }

    o = min_s->head;
    while (o) {
        aux = o->next;

        o->next = max_s->head;
        o->s = max_s;
        max_s->head = o;

        o = aux;
    }

    max_s->length += min_s->length;
}

int main(void)
{
    int n, m, i, op, x, y;

    freopen("disjoint.in", "r", stdin);
    freopen("disjoint.out", "w", stdout);

    scanf("%d %d", &n, &m);

    for (i = 1; i <= n; i++) {
        make_set(i);
    }

    while (m--) {
        scanf("%d %d %d", &op, &x, &y);

        if (op == 1) {
            union_op(x, y);
        } else {
            if (find_set(x) == find_set(y)) {
                puts("DA");
            } else {
                puts("NU");
            }
        }
    }

    return 0;
}