Pagini recente » Cod sursa (job #3175430) | Cod sursa (job #2152983) | Cod sursa (job #1976950) | Cod sursa (job #3241509) | Cod sursa (job #1693435)
#include <fstream>
#include <cstdio>
//using namespace std;
class disjoint_sets {
private:
unsigned *parents;
unsigned *set_identifier;
unsigned forest_size;
public:
disjoint_sets(unsigned size)
: forest_size(size)
{
parents = new unsigned[size];
set_identifier = new unsigned[size];
for (unsigned idx = 1; idx <= forest_size; ++idx) {
parents[idx] = idx;
set_identifier[idx] = 1;
}
}
~disjoint_sets()
{
delete [] parents;
delete [] set_identifier;
}
unsigned find_set_of(unsigned elem)
{
unsigned root = 0;
unsigned temp = 0;
if (elem > forest_size)
return root;
/*find the root of the set*/
for(root = elem; parents[root] != root; root = parents[root]);
/*compress the paths*/
while(parents[elem] != elem)
{
temp = parents[elem];
parents[elem] = root;
elem = temp;
}
return root;
}
void merge_sets_of_elems(unsigned e1, unsigned e2)
{
if (find_set_of(e1) == find_set_of(e2))
return;
if (set_identifier[e1] > set_identifier[e2])
parents[e2] = e1;
else
parents[e1] = e2;
if (set_identifier[e1] == set_identifier[e2])
++set_identifier[e2];
}
};
int main() {
std::ifstream cin("disjoint.in");
std::ofstream cout("disjoint.out");
disjoint_sets dsets(10001);
unsigned N;
unsigned M;
cin >> N >> M;
for (unsigned i = 0; i < M; ++i) {
unsigned comm, arg1, arg2;
cin >> comm >> arg1 >> arg2;
if (2 == comm) {
if (dsets.find_set_of(arg1) == dsets.find_set_of(arg2))
cout << "DA\n";
else
cout << "NU\n";
} else
dsets.merge_sets_of_elems(arg1, arg2);
}
return 0;
}