Pagini recente » Cod sursa (job #691169) | Cod sursa (job #1950550) | Cod sursa (job #2661974) | Cod sursa (job #434012) | Cod sursa (job #2232345)
#include <stdio.h>
#define max(a, b) (((a) > (b)) ? (a) : (b))
#define NMAX 100001
int n, m;
int trees[NMAX], heights[NMAX];
int get_root(int x)
{
int root_x, y, aux;
// get root
root_x = x;
while (root_x != trees[root_x])
root_x = trees[root_x];
// compress the paths
y = x;
while (y != root_x) {
aux = trees[y];
trees[y] = root_x;
y = aux;
}
return root_x;
}
void join(int x, int y)
{
x = get_root(x);
y = get_root(y);
// link the smaller tree to the bigger one
if (heights[x] < heights[y]) {
trees[x] = y;
heights[y] = max(heights[y], 1 + heights[x]);
} else {
trees[y] = x;
heights[x] = max(heights[x], 1 + heights[y]);
}
}
int are_joint(int x, int y)
{
return get_root(x) == get_root(y);
}
int main()
{
freopen("disjoint.in", "r", stdin);
freopen("disjoint.out", "w", stdout);
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++)
trees[i] = i;
int cod, x, y;
for (int i = 0; i < m; i++) {
scanf("%d%d%d", &cod, &x, &y);
switch (cod) {
case 1:
join(x, y);
break;
case 2:
if (are_joint(x, y))
printf("DA\n");
else
printf("NU\n");
break;
}
}
return 0;
}