Pagini recente » Cod sursa (job #2896708) | Cod sursa (job #1408935) | Cod sursa (job #2368782) | Cod sursa (job #130222) | Cod sursa (job #2079864)
#include <bits/stdc++.h>
using namespace std;
class disjoint_set_union {
public:
disjoint_set_union(size_t size) :
data_(size, -1) {
}
void join(int x, int y) {
x = get_root(x);
y = get_root(y);
if (x == y)
return;
//join by rank
if (data_[x] < data_[y]) {
data_[x] += data_[y];
data_[y] = x;
}
else {
data_[y] += data_[x];
data_[x] = y;
}
}
bool query(int x, int y) {
return get_root(x) == get_root(y);
}
private:
int get_root(int x) {
//find root
int aux = x;
while (data_[x] > 0)
x = data_[x];
int root = x;
//compress
x = aux;
while (x != root) {
aux = data_[x];
data_[x] = root;
x = aux;
}
return root;
}
vector< int > data_;
};
void solve() {
size_t element_count, query_count;
cin >> element_count >> query_count;
disjoint_set_union dsu(element_count + 1);
while (query_count--) {
int operation, x, y;
cin >> operation >> x >> y;
if (operation == 1)
dsu.join(x, y);
else
cout << (dsu.query(x, y) ? "DA" : "NU") << '\n';
}
}
int main() {
assert(freopen("disjoint.in", "r", stdin));
assert(freopen("disjoint.out", "w", stdout));
cin.tie(nullptr);
ios_base::sync_with_stdio(false);
solve();
return 0;
}