Pagini recente » Cod sursa (job #1338368) | Cod sursa (job #1396450) | Cod sursa (job #1353854) | Cod sursa (job #2493633) | Cod sursa (job #2739760)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
int const N = 1e5 + 5;
vector<int> height(N), group(N); // height of a tree and the number of the set where is located each element
int n, m;
int find_root(int x) {
int node = x;
while (group[node] != node) {
node = group[node];
}
//build a path between all nodes directly to the root 'node' in the tree
//in this way we optimize the algorithm to not lose time in searching
while (group[x] != x) {
int aux = group[x];
group[x] = node;
x = aux;
}
return node;
}
void unite(int x, int y) {
if (height[x] > height[y]) {
group[y] = x;
} else {
group[x] = y;
}
if (height[x] == height[y]) {
height[y]++;
}
}
int main() {
ios::sync_with_stdio(0), cin.tie(0);
cin >> n >> m;
for (int i = 1; i <= n; ++i) {
height[i] = 1;
group[i] = i;
}
for (int i = 1; i <= m; ++i) {
int code, x, y;
cin >> code >> x >> y;
if (code == 1) {
unite(find_root(x), find_root(y));
} else {
if (find_root(x) == find_root(y)) {
cout << "DA\n";
} else {
cout << "NU\n";
}
}
}
return 0;
}