Mai intai trebuie sa te autentifici.
Cod sursa(job #2226052)
Utilizator | Data | 29 iulie 2018 14:02:59 | |
---|---|---|---|
Problema | Paduri de multimi disjuncte | Scor | 100 |
Compilator | cpp | Status | done |
Runda | Arhiva educationala | Marime | 1.5 kb |
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
typedef struct node {
int key;
struct node* parent;
int rank;
}node;
node* nodes[100001];
node* make_set(int key) {
node* n = (node *)malloc(sizeof(node));
if (n == NULL) {
perror("malloc failed");
exit(1);
}
n->key = key;
n->parent = n;
n->rank = 0;
return n;
}
node* find_set(node* x) {
if (x->parent != x) {
x->parent = find_set(x->parent);
}
return x->parent;
}
void link(node* x, node* y) {
if (x->rank > y->rank) {
y->parent = x;
}
else if (y->rank > x->rank) {
x->parent = y;
}
else {
x->parent = y;
y->rank = y->rank + 1;
}
}
void unite(node* x, node* y) {
link(find_set(x), find_set(y));
}
int main() {
FILE* ip;
ip = fopen("disjoint.in", "r");
if (ip == NULL) {
perror("Could not open input file");
return 1;
}
FILE* op;
op = fopen("disjoint.out", "w");
if (op == NULL) {
perror("Could not open output file");
return 1;
}
int n, m;
fscanf(ip, "%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
nodes[i] = make_set(i);
}
for (int i = 0; i < m; i++) {
int cod, x, y;
fscanf(ip, "%d%d%d", &cod, &x, &y);
if (cod == 1) {
unite(nodes[x], nodes[y]);
}
else if (cod == 2) {
if (find_set(nodes[x]) == find_set(nodes[y])) {
fprintf(op, "DA\n");
}
else {
fprintf(op, "NU\n");
}
}
}
fclose(ip);
fclose(op);
return 0;
}