2019-10-01 18:46:18 +03:00
|
|
|
#include <stdio.h>
|
|
|
|
|
2019-10-01 15:37:01 +03:00
|
|
|
int p[1000000];
|
|
|
|
int find(int x)
|
|
|
|
{
|
2020-05-29 23:23:24 +03:00
|
|
|
if (p[x] == x)
|
|
|
|
{
|
|
|
|
return x;
|
|
|
|
}
|
|
|
|
else
|
|
|
|
{
|
|
|
|
p[x] = find(p[x]);
|
|
|
|
return p[x];
|
|
|
|
}
|
2019-10-01 15:37:01 +03:00
|
|
|
}
|
|
|
|
// Call to function join(int x, int y) to join PARAM x and y
|
2020-05-29 23:23:24 +03:00
|
|
|
void join(int x, int y) { p[find(x)] = find(y); }
|
2019-10-01 15:37:01 +03:00
|
|
|
|
2020-05-29 23:23:24 +03:00
|
|
|
int main()
|
2019-10-01 18:46:18 +03:00
|
|
|
{
|
|
|
|
// Have all array indexes that you need to use refrence themselves
|
|
|
|
for (int i = 0; i < 10; i++)
|
|
|
|
{
|
|
|
|
p[i] = i;
|
|
|
|
}
|
|
|
|
// p = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}
|
|
|
|
join(3, 5);
|
|
|
|
// Now 3 and 5 are groupped together, that is find(3) = find(5)
|
|
|
|
// p = {0, 1, 2, 5, 4, 5, 6, 7, 8, 9}
|
|
|
|
join(3, 8);
|
|
|
|
// Now 3, 5 and are groupped together, find(3) = find(5) = find(8)
|
|
|
|
// p = {0, 1, 2, 5, 4, 8, 6, 7, 8, 9}
|
|
|
|
join(0, 5);
|
2020-05-29 23:23:24 +03:00
|
|
|
if (find(0) == find(3))
|
2019-10-01 18:46:18 +03:00
|
|
|
{
|
|
|
|
printf("0 and 3 are groupped together\n");
|
|
|
|
}
|
|
|
|
printf("The array is now: ");
|
2020-05-29 23:23:24 +03:00
|
|
|
for (int i = 0; i < 10; i++)
|
2019-10-01 18:46:18 +03:00
|
|
|
{
|
|
|
|
printf("%d ", p[i]);
|
|
|
|
}
|
|
|
|
printf("\n");
|
|
|
|
|
2019-10-01 15:37:01 +03:00
|
|
|
return 0;
|
|
|
|
}
|