Cod sursa(job #1025557)

Utilizator gallexdAlex Gabor gallexd Data 10 noiembrie 2013 11:13:03
Problema Paduri de multimi disjuncte Scor 70
Compilator cpp Status done
Runda Arhiva educationala Marime 1.16 kb
#include <cstdio>
#include <algorithm>
using namespace std;

struct Node {
    Node() {rad=NULL;};
    Node *rad;
};

Node *copacul[100010];
int H[100010];

int N, M;

Node *root(int x) {
    Node *R = copacul[x];
    while (R->rad)
        R = R->rad;
   /* Node *t = copacul[x], *aux;
    while (t->rad) {
        aux = t;
        t = t->rad;
        aux->rad = R;
    }*/
    return R;
}

void joint(int x, int y) {
    if (H[x] > H[y])
        swap(x, y);
    Node *Rx = root(x);
    Node *Ry = root(y);
    Rx->rad = Ry;
    if (H[x] + 1 > H[y])
        H[y] = H[x] + 1;
}

void check(int x, int y) {
    Node *Rx = root(x);
    Node *Ry = root(y);
    if (Rx == Ry) printf("DA\n");
    else printf("NU\n");
}

int main () {

    freopen("disjoint.in","rt",stdin);
    freopen("disjoint.out","wt",stdout);

    scanf("%d %d\n", &N, &M);
    for (int type, x, y; M; --M) {
        scanf("%d %d %d\n", &type, &x, &y);
        if (!copacul[x]) copacul[x] = new Node;
        if (!copacul[y]) copacul[y] = new Node;
        if (type == 1)
            joint(x,y);
        else
            check(x, y);
    }
    return 0;
}