Pagini recente » Cod sursa (job #2715559) | Cod sursa (job #2442703) | Cod sursa (job #3228163) | Cod sursa (job #3234205) | Cod sursa (job #3300332)
#include <iostream>
using namespace std;
int tata[100005];
int heights[100005];
int getRoot(int node) {
int root = node;
while (root != tata[root]) {
root = tata[root];
}
while (node != root) {
int nextNode = tata[node];
tata[node] = root;
node = nextNode;
}
return root;
}
void unite(int x, int y) {
int rootX = getRoot(x);
int rootY = getRoot(y);
if (heights[rootX] < heights[rootY]) {
tata[rootX] = rootY;
} else if (heights[rootX] > heights[rootY]) {
tata[rootY] = rootX;
} else {
tata[rootX] = rootY;
heights[rootY] += 1;
}
}
int main() {
freopen("disjoint.in", "r", stdin);
freopen("disjoint.out", "w", stdout);
int n, m;
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
tata[i] = i;
heights[i] = 1;
}
// O(N * M) = 10 ^ 10
for (int i = 0; i < m; ++i) {
int op, x, y;
cin >> op >> x >> y;
if (op == 1) {
unite(x, y);
} else {
if (getRoot(x) == getRoot(y)) {
cout << "DA\n";
} else {
cout << "NU\n";
}
}
}
return 0;
}