Pagini recente » Istoria paginii runda/lot-2015-anime.edition/clasament | Cod sursa (job #2818395) | Cod sursa (job #2939230) | Cod sursa (job #529305) | Cod sursa (job #1195473)
#include <stdio.h>
#include <stdlib.h>
#define DIM 100001
typedef enum op {
toUnite = 1,
toQuery
} operationCode;
void unite(int x, int y, int *Rank, int *Father)
{
// apply here the rank heuristics
if (Rank[x] > Rank[y])
Father[y] = x;
else
Father[x] = y;
if (Rank[x] == Rank[y])
Rank[x]++;
}
int find(int x, int *Rank, int *Father)
{
int R;
for (R = Father[x]; R != Father[R]; R = Father[R]);
// apply here the road heuristics
for (; x != Father[x];) {
int y = Father[x];
Father[x] = R;
x = y;
}
return R;
}
void freeMemory(int *Rank, int *Father)
{
free(Rank);
free(Father);
}
int main()
{
freopen("disjoint.in", "r", stdin);
freopen("disjoint.out", "w", stdout);
int *Father, *Rank, N, M, i, x, y;
Father = (int*)malloc(DIM * sizeof(int));
Rank = (int*)malloc(DIM * sizeof(int));
scanf("%d%d", &N, &M);
for (i = 1; i <= N; i++) {
Father[i] = i; // every node first will point to itself
Rank[i] = 1; // the rank will be 1 for all the trees, at the beginning, it also can be 0
}
int operation;
for (i = 1; i <= M; i++) {
scanf("%d%d%d", &operation, &x, &y);
if (operation == toUnite) {
// unite the roots of the trees
unite(find(x, Rank, Father), find(y, Rank, Father), Rank, Father);
}
else if (operation == toQuery) {
if (find(x, Rank, Father) == find(y, Rank, Father))
printf("DA\n");
else
printf("NU\n");
}
}
freeMemory(Rank, Father);
return 0;
}