Pagini recente » Cod sursa (job #865567) | Cod sursa (job #2281527) | Cod sursa (job #1193198) | Cod sursa (job #3125369) | Cod sursa (job #3252907)
#include <fstream>
#include <vector>
struct DSU {
std::vector<int> parent;
std::vector<int> height;
DSU(int n) {
parent.resize(n);
height.resize(n);
for (int i = 0; i < n; i += 1) {
parent[i] = i, height[i] = 1;
}
}
int Find(int x) {
int root = x;
while (root != parent[root]) {
root = parent[root];
}
int elem = x;
while (elem != root) {
int temp = parent[elem];
parent[elem] = root;
elem = temp;
}
return root;
}
void Union(int x, int y) {
x = Find(x), y = Find(y);
if (height[x] < height[y]) {
parent[x] = y;
} else {
parent[y] = x;
if (height[x] == height[y]) {
height[x] += 1;
}
}
}
};
int main() {
std::ifstream fin("disjoint.in");
std::ofstream fout("disjoint.out");
int n, m; fin >> n >> m;
DSU dsu(n);
for (int i = 0; i < m; i += 1) {
int op, x, y; fin >> op >> x >> y; x -= 1, y -= 1;
if (op == 1) {
dsu.Union(x, y);
} else {
fout << (dsu.Find(x) == dsu.Find(y) ? "DA" : "NU") << '\n';
}
}
fin.close(), fout.close();
return 0;
}