Pagini recente » Borderou de evaluare (job #1116427) | Cod sursa (job #3332046) | Borderou de evaluare (job #1256078) | Cod sursa (job #1112802) | Cod sursa (job #3328544)
#include <fstream>
std::ifstream in("disjoint.in");
std::ofstream out("disjoint.out");
unsigned parent_of[100001];
unsigned size_of[100001];
unsigned root_of(unsigned node) {
unsigned root = node;
while(parent_of[root] != root) {
root = parent_of[root];
}
unsigned aux;
while(parent_of[node] != root) {
aux = node;
node = parent_of[node];
parent_of[aux] = root;
}
return root;
}
void merge(unsigned a, unsigned b) {
unsigned root_of_a = root_of(a), root_of_b = root_of(b);
if(size_of[root_of_a] > size_of[root_of_b]) {
parent_of[root_of_b] = root_of_a;
return;
}
if(size_of[root_of_a] < size_of[root_of_b]) {
parent_of[root_of_a] = root_of_b;
return;
}
parent_of[root_of_a] = root_of_b;
size_of[root_of_a] += 1;
}
int main() {
unsigned N, ops;
in >> N >> ops;
for(unsigned i = 1; i <= N; i += 1) {
parent_of[i] = i;
size_of[i] = 1;
}
unsigned type, a, b;
for(unsigned op = 0; op < ops; op += 1) {
in >> type >> a >> b;
if (type == 1) {
merge(a, b);
continue;
}
if(root_of(a) == root_of(b)) out << "DA\n";
else out << "NU\n";
}
}