Pagini recente » Cod sursa (job #2444528) | Istoria paginii runda/emagcluj_10_2016/clasament | Cod sursa (job #1984528) | Cod sursa (job #2224734) | Cod sursa (job #2678703)
#include <bits/stdc++.h>
using namespace std;
class DisjointSets {
private:
vector<int> parent;
vector<int> rank;
public:
DisjointSets(int n) {
for (int i = 0; i < n; i++)
make_set(i);
}
~DisjointSets() {
parent.clear();
rank.clear();
}
void make_set(int x) {
parent.push_back(x);
rank.push_back(0);
}
int find_set(int x) {
vector<int> queue;
while (parent[x] != x) {
queue.push_back(x);
x = parent[x];
}
for (int it: queue)
parent[it] = x;
queue.clear();
return x;
}
void union_set(int x, int y) {
int rx = find_set(x); // alias reprezentatnul lui x, respectiv y
int ry = find_set(y);
if (rank[rx] <= rank[ry]) {
parent[rx] = ry;
rank[rx] == rank[ry] ? rank[ry]++ : false;
}
else
parent[ry] = rx;
}
void show() {
for (int i = 0; i < parent.size(); i++)
cout << i << " " << parent[i] << " " << rank[i] << endl;
}
};
void solve(int n, int m) {
DisjointSets disjointSets(n);
int op;
int x, y;
for (int i = 0; i < m; i++) {
cin >> op >> x >> y;
switch (op) {
case 1 :
disjointSets.union_set(x - 1, y - 1);
break;
case 2 :
cout << ((disjointSets.find_set(x - 1) == disjointSets.find_set(y - 1)) ? "DA" : "NU") << "\n";
}
}
}
int main() {
freopen("disjoint.in", "r", stdin);
freopen("disjoint.out", "w", stdout);
int n, m;
cin >> n >> m;
solve(n, m);
return 0;
}