Pagini recente » Cod sursa (job #1628225) | Cod sursa (job #845359) | Cod sursa (job #1488633) | Cod sursa (job #1764494) | Cod sursa (job #2572726)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
class Forest {
private:
vector<int> height;
vector<int> father;
public:
Forest(int n) :
height(n + 1), father(n + 1) { }
int find(int x) {
int root = x;
while (father[root])
root = father[root];
while (father[x]) {
int aux = father[x];
father[x] = root;
x = aux;
}
return root;
}
void unite(int x, int y) {
int rootX = find(x);
int rootY = find(y);
if (rootX == rootY)
return;
if (height[rootX] < height[rootY])
father[rootX] = rootY;
else {
father[rootY] = rootX;
if (height[rootX] == height[rootY])
height[rootX]++;
}
}
};
int main() {
int n, q; fin >> n >> q;
Forest forest(n);
for (int i = 0; i < q; i++) {
int t, x, y; fin >> t >> x >> y;
if (t == 1)
forest.unite(x, y);
else
fout << (forest.find(x) == forest.find(y) ? "DA\n" : "NU\n");
}
fout.close();
return 0;
}