Pagini recente » Cod sursa (job #1728290) | Cod sursa (job #320928) | Cod sursa (job #901617) | Cod sursa (job #1122739) | Cod sursa (job #742258)
Cod sursa(job #742258)
#include <stdio.h>
#define NMAX 100002
int TT[NMAX], RG[NMAX];
int N, M;
int find(int x)
{
int R, y;
// go up the tree until we find a node that points to itself
for(R = x; TT[R] != R; R = TT[R]);
// apply road compression so we get better run time
for(; TT[x] != x;)
{
y = TT[x];
TT[x] = R;
x = y;
}
return R;
}
void unite(int x, int y)
{
// unite the set with smaller rank to the one with bigger rank
if(RG[x] > RG[y])
TT[y] = x;
else
TT[x] = y;
// if ranks were equal, raise the rank of the new set with 1
if(RG[x] == RG[y])
RG[y] ++;
}
int main()
{
FILE* f, g;
f = freopen("disjoint.in", "r", stdin);
g = freopen("disjoint.out", "w", stdout);
scanf("%d %d", &N, &M); // read the number of sets and the number of operations
int i, x, y, cd;
// at first every node points to itself and every tree has rank 1
for(i = 1; i <= N; i++)
{
TT[i] = i; // every node points to itself
RG[i] = 1; // every tree has rank = 1
}
for(i = 1; i<=M; i++) // read the operations
{
scanf("%d %d %d", &cd, &x, &y);
if(cd == 2) // if we have to check whether they are in the same tree
{
if(find(x) == find(y)) // check and write appropriate message
printf("DA\n");
else
printf("NU\n");
}
else // if we have to unite two trees
{
if(find(x) == find(y)) // if they are in the same tree, it is an error
{
fprintf(stderr, "%d ", i);
return 0;
}
unite(find(x), find(y)); // if they are in disjoint trees, we unite them
}
}
f.close();
g.close();
fclose(stdin);
fclose(stdout);
return 0;
}