Pagini recente » Cod sursa (job #764825) | Cod sursa (job #2813436) | Cod sursa (job #3179856) | Cod sursa (job #136387) | Cod sursa (job #2525965)
#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];
int aux;
while (father[x]) {
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, m;
fin >> n >> m;
Forest forest(n);
for (int i = 0; i < m; i++) {
int x, y, z; fin >> x >> y >> z;
if (x == 1)
forest.unite(y, z);
else
fout << (forest.find(y) == forest.find(z) ? "DA\n" : "NU\n");
}
fout.close();
return 0;
}