Pagini recente » Cod sursa (job #3250709) | Cod sursa (job #1611251) | Cod sursa (job #889952) | Cod sursa (job #488665) | Cod sursa (job #2811875)
#include <iostream>
#include <vector>
#include <fstream>
using namespace std;
ifstream f("disjoint.in");
ofstream g("disjoint.out");
const int max_nr_nodes = 100001;
struct Node {
int parent;
int node_rank;
};
vector<Node> parent_vector(max_nr_nodes);
int find_root_node(int current_node) {
if (parent_vector[current_node].parent == -1) {
return current_node;
}
return parent_vector[current_node].parent = find_root_node(parent_vector[current_node].parent);
}
void make_sets_union(int x, int y) {
int x_root_parent = find_root_node(x);
int y_root_parent = find_root_node(y);
if (parent_vector[x_root_parent].node_rank > parent_vector[y_root_parent].node_rank) {
parent_vector[y_root_parent].parent = x;
} else if (parent_vector[x_root_parent].node_rank < parent_vector[y_root_parent].node_rank) {
parent_vector[x_root_parent].parent = y;
} else {
parent_vector[y_root_parent].parent = x;
++parent_vector[x_root_parent].node_rank;
}
}
bool in_same_set(int x, int y) {
int x_root_parent = find_root_node(x);
int y_root_parent = find_root_node(y);
return x_root_parent == y_root_parent;
}
int main() {
int n, m;
f >> n >> m;
for (int i = 1; i <= n; ++i) {
parent_vector[i].parent = -1;
parent_vector[i].node_rank = 0;
}
for (int i = 1; i <= m; ++i) {
int operation, x, y;
f >> operation >> x >> y;
if (operation == 1) {
make_sets_union(x, y);
} else {
if (in_same_set(x, y)) {
g << "DA\n";
} else {
g << "NU\n";
}
}
}
return 0;
}