Cod sursa(job #978553)

Utilizator stefanfStefan Fulger stefanf Data 29 iulie 2013 00:26:42
Problema Paduri de multimi disjuncte Scor 100
Compilator c Status done
Runda Arhiva educationala Marime 1.54 kb
#include<stdio.h>
#include<stdlib.h>

struct node {
    int rank;
    struct node* parent;
};

struct node* makeNode() {
    struct node* nod = malloc(sizeof(struct node));
    nod->rank = 0;
    nod->parent = NULL;

    return nod;
}

struct node** makeSet(int n) {
    struct node** set = malloc((n+1) * sizeof(struct node*));
    int i;
    for(i = 0; i <= n; i++)
        set[i] = makeNode();

    return set;
}

struct node* findSet(struct node* leaf) {
    if (leaf->parent == NULL)
        return leaf;

    leaf->parent = findSet(leaf->parent);
    return leaf->parent;
}

void unionSet(struct node* x, struct node* y) {
    struct node* xRoot = findSet(x);
    struct node* yRoot = findSet(y);

    if (xRoot == yRoot)
        return;
        
    if(xRoot->rank < yRoot->rank)
        xRoot->parent = yRoot;
    else if (xRoot->rank > yRoot->rank)
        yRoot->parent = xRoot;
    else {
        yRoot->parent = xRoot;
        xRoot->rank++;
    }
}

int sameSet(struct node* x, struct node* y) {
    struct node* xRoot = findSet(x);
    struct node* yRoot = findSet(y);

    if (xRoot == yRoot)
        return 1;
    else 
        return 0;
}

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

    int n, m;
    int o, x, y, i;
    scanf("%d %d", &n, &m);
    struct node** set = makeSet(n);
    for (i = 0; i < m; i++) {
        scanf("%d %d %d", &o, &x, &y);
        if (o == 1)
            unionSet(set[x], set[y]);
        else
            printf("%s\n", (sameSet(set[x], set[y])) ? "DA" : "NU");
    }
    return 0;
}