Pagini recente » Cod sursa (job #1313493) | Cod sursa (job #297407) | Cod sursa (job #300199) | Cod sursa (job #2306811) | Cod sursa (job #646202)
Cod sursa(job #646202)
#include <stdio.h>
#include <stdlib.h>
unsigned int N, M, *parent, *heights;
unsigned int findRoot(unsigned int x)
{
unsigned int root, temp, tempParent;
temp = x;
while(parent[temp])
temp = parent[temp];
root = temp; temp = x;
while(parent[temp])
{
tempParent = parent[temp];
parent[temp] = root;
temp = tempParent;
}
return root;
}
void op1(unsigned int x, unsigned int y)
{
unsigned int rx = findRoot(x);
unsigned int ry = findRoot(y);
if(heights[rx] > heights[ry])
parent[ry] = rx;
else if(heights[rx] < heights[ry])
{
parent[rx] = ry;
}
else
{
++heights[rx];
parent[ry]= rx;
}
}
short op2(unsigned int x, unsigned int y)
{
return findRoot(x) == findRoot(y);
}
int main()
{
unsigned int op, x, y, i;
freopen("disjoint.in", "r", stdin);
freopen("disjoint.out", "w", stdout);
scanf("%u %u", &N, &M);
parent = (unsigned int*)malloc(sizeof(unsigned int) * (N + 1));
heights = (unsigned int*)malloc(sizeof(unsigned int) * (N + 1));
for(i = 1; i <= N; ++i)
parent[i] = heights[i] = 0;
while(M--)
{
scanf("%u %u %u", &op, &x, &y);
switch(op)
{
case 1:
op1(x, y);
break;
case 2:
if(op2(x, y))
puts("DA");
else
puts("NU");
break;
}
}
return 0;
}