Pagini recente » Cod sursa (job #1744077) | Cod sursa (job #702808) | Cod sursa (job #29223) | Cod sursa (job #1637772) | Cod sursa (job #2940648)
#include <algorithm>
#include <fstream>
#include <limits>
#include <vector>
using std::vector;
template <class T> class DSU {
vector<T> parent;
vector<int> height;
public:
DSU(int setCount) {
parent.resize(setCount + 1);
height.resize(setCount + 1, 0);
}
void makeSet(T x) { parent[x] = x; }
T getRepr(T x) {
if (parent[x] == x) {
return x;
}
return parent[x] = getRepr(parent[x]);
}
void unite(T x, T y) {
auto xr = getRepr(x);
auto yr = getRepr(y);
if (height[xr] < height[yr]) {
parent[yr] = xr;
if (height[xr] == height[yr]) height[xr]++;
} else {
parent[xr] = yr;
if (height[xr] == height[yr]) height[yr]++;
}
}
};
int main() {
std::ifstream fin("disjoint.in");
int setCount, opCount;
fin >> setCount >> opCount;
DSU<int> dsu(setCount);
for (int i = 1; i <= setCount; ++i) {
dsu.makeSet(i);
}
std::ofstream fout("disjoint.out");
for (int i = 0; i < opCount; ++i) {
int op, x, y;
fin >> op >> x >> y;
if (op == 1) {
dsu.unite(x, y);
} else {
if (dsu.getRepr(x) == dsu.getRepr(y)) {
fout << "DA\n";
} else {
fout << "NU\n";
}
}
}
fin.close();
fout.close();
return 0;
}