Pagini recente » Cod sursa (job #1014572) | Cod sursa (job #3167185) | Cod sursa (job #215295) | Cod sursa (job #2833551) | Cod sursa (job #3255309)
#include <fstream>
#include <vector>
using namespace std;
ifstream cin("disjoint.in");
ofstream cout("disjoint.out");
class DisjointSet {
private:
std::vector<int> set;
public:
DisjointSet(int size) : set{ vector<int>(size, -1) } {}
int Find(int x) {
while (set[x] >= 0) {
int parent = set[x];
if (set[parent] >= 0) {
set[x] = set[parent];
}
x = parent;
}
return x;
}
void Union(int x, int y) {
int rootx = Find(x);
int rooty = Find(y);
if (set[rootx] < set[rooty]) { // add y to x
set[rootx] += set[rooty];
set[rooty] = rootx;
}
else { // add x to y
set[rooty] += set[rootx];
set[rootx] = rooty;
}
}
int size(int x) {
x = Find(x);
return -set[x];
}
};
int main()
{
int n, m, op, x, y;
cin >> n >> m;
DisjointSet s(n+1);
for (int i = 0; i < m; i++) {
cin >> op >> x >> y;
if (op == 1) {
s.Union(x, y);
}
else {
if (s.Find(x) == s.Find(y)) {
cout << "DA\n";
}
else {
cout << "NU\n";
}
}
}
}