Pagini recente » Cod sursa (job #1060457) | Cod sursa (job #1883904) | Cod sursa (job #1638635) | Cod sursa (job #2844160) | Cod sursa (job #978553)
Cod sursa(job #978553)
#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;
}