Pagini recente » Cod sursa (job #329252) | Cod sursa (job #1016301) | Cod sursa (job #2653224) | Cod sursa (job #2363710) | Cod sursa (job #2605917)
#include <stdio.h>
#include <stdlib.h>
int Find(int x, int *c) {
int y = x, t;
while(y != c[y])
y = c[y];
while(x != y) {
t = c[x];
c[x] = y;
x = t;
}
return x;
}
void Unite(int x, int y, int *c) {
x = Find(x, c);
y = Find(y, c);
c[y] = x;
}
int main() {
int N, M, *c, type, A, B;
FILE *input = fopen("disjoint.in", "r");
FILE *output = fopen("disjoint.out", "w");
fscanf(input, "%d%d", &N, &M);
c = (int *) calloc(N + 1, sizeof(int));
for(int i = 1; i <= N; i++)
c[i] = i;
for(int i = 1; i <= M; i++) {
fscanf(input, "%d %d %d", &type, &A, &B);
if(type == 1) {
if((A = Find(A, c)) != (B = Find(B, c)))
Unite(A, B, c);
} else {
if(Find(A, c) == Find(B, c)) {
fprintf(output, "DA\n");
} else {
fprintf(output, "NU\n");
}
}
}
free(c);
fclose(input);
fclose(output);
return 0;
}