Pagini recente » Cod sursa (job #2640421) | Cod sursa (job #509798) | Cod sursa (job #2528688) | Cod sursa (job #2285597) | Cod sursa (job #254812)
Cod sursa(job #254812)
#include <stdio.h>
#include <stdlib.h>
#define MAX 100001
#define in "disjoint.in"
#define out "disjoint.out"
struct el_mult
{
int parent, height;
};
struct el_mult set[MAX];
int find_parent(int x)
{
if (set[x].parent == 0)
return x;
else
{
set[x].parent = find_parent(set[x].parent);
return set[x].parent;
}
}
void reunion(int x, int y)
{
int px, py;
px = find_parent(x);
py = find_parent(y);
if (set[px].height < set[py].height)
{
set[px].parent = py;
} else if (set[px].height > set[py].height)
{
set[py].parent = px;
} else if (px != py)
{
set[py].parent = px;
set[px].height++;
}
}
int find(int x, int y)
{
int px, py;
px = find_parent(x);
py = find_parent(y);
return px == py;
}
int main()
{
int i, z, m, n, x, y;
FILE *fin, *fout;
if ((fin = fopen(in, "r")) == NULL)
{
printf("Eroare \n");
exit(-1);
}
//read dimension of vectors
fscanf(fin, "%d%d", &n, &m);
//read the vectors
for (i = 1; i<=n ; i++)
{
set[i].parent = 0;
set[i].height = 0;
}
fout = fopen(out, "w");
for (i = 0; i < m; i++)
{
fscanf(fin, "%d%d%d", &x, &y, &z);
if (x == 1)
{
reunion(y, z);
}
else if (x == 2)
{
z = find(y, z);
fprintf(fout, "%s\n", z == 0 ? "NU" : "DA");
}
}
fclose(fin);
fclose(fout);
return 0;
}