Pagini recente » Cod sursa (job #1362220) | Cod sursa (job #2414973) | Cod sursa (job #878271) | Cod sursa (job #263294) | Cod sursa (job #2470226)
#include <fstream>
#define N_MAX 100000
using namespace std;
size_t id[N_MAX + 1];
size_t sz[N_MAX + 1];
void path_compression(size_t x, size_t root)
{
size_t next;
while(x != root)
{
next = id[x];
id[x] = root;
x = next;
}
return;
}
size_t find_root(size_t x)
{
size_t root = x;
while(root != id[root]) root = id[root];
path_compression(x, root);
return root;
}
string same_set(size_t x, size_t y)
{
if(find_root(x) == find_root(y)) return "DA";
return "NU";
}
void union_sets(size_t x, size_t y)
{
size_t rootX = find_root(x);
size_t rootY = find_root(y);
if(rootX == rootY) return;
if(sz[rootX] > sz[rootY])
{
id[rootY] = rootX;
sz[rootX] += sz[rootY];
}
else {
id[rootX] = rootY;
sz[rootY] += sz[rootX];
}
return;
}
void disjoint_init()
{
for(size_t i = 0; i <= N_MAX; ++i)
{
sz[i] = 1;
id[i] = i;
}
}
int main()
{
disjoint_init();
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
size_t N, M;
fin >> N >> M;
size_t op, x, y;
for(size_t i = 1; i <= M; ++i)
{
fin >> op >> x >> y;
if(op == 1) union_sets(x, y);
else fout << same_set(x, y) << '\n';
}
}