Pagini recente » Cod sursa (job #1837780) | Cod sursa (job #2665229) | Cod sursa (job #1425460) | Cod sursa (job #1425487) | Cod sursa (job #792911)
Cod sursa(job #792911)
#include <cstdio>
const int MAX_SIZE(100001);
int forest [MAX_SIZE];
// Because sets are numbered starting from 1, I can count the depth of each tree
// and skip the -1 initialization, but I choosed to solve the general case though
inline void initialize (int n)
{
for (int *iterator(forest + 1), *end(forest + n) ; iterator <= end ; ++iterator)
*iterator = -1;
}
int find_set (int x)
{
if (forest[x] < 0)
return x;
forest[x] = find_set(forest[x]); // path compression
return forest[x];
}
inline void set_union (int x, int y)
{
x = find_set(x);
y = find_set(y);
if (x == y)
return;
if (forest[y] < forest[x])
{
x ^= y;
y ^= x;
x ^= y;
}
forest[x] += forest[y];
forest[y] = x;
}
int main (void)
{
std::freopen("disjoint.in","r",stdin);
std::freopen("disjoint.out","w",stdout);
int n, m;
std::scanf("%d%d",&n,&m);
initialize(n);
char operation, *operation_ptr(&operation);
int x, *x_ptr(&x), y, *y_ptr(&y);
do
{
std::scanf("\n%c%d%d",operation_ptr,x_ptr,y_ptr);
if (operation == 1)
set_union(x,y);
else
std::printf("%s\n",(find_set(x) == find_set(y) ? "DA" : "NU"));
--m;
}
while (m);
std::fclose(stdin);
std::fclose(stdin);
return 0;
}