Pagini recente » Cod sursa (job #1429754) | Cod sursa (job #2379001) | Cod sursa (job #326617) | Cod sursa (job #619561) | Cod sursa (job #3197491)
#include <fstream>
#include <vector>
using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");
#define cin in
#define cout out
class DSU {
int n;
vector<int> par, size;
public:
DSU(int _n) : n(_n) {
par.resize(n + 1);
for (int i = 1; i <= n; ++i) {
par[i] = i;
}
size.assign(n + 1, 1);
}
int getRoot(int x) {
int root = x;
while (root != par[root]) {
root = par[root];
}
while (x != par[x]) {
int aux = par[x];
par[x] = root;
x = aux;
}
return root;
}
bool unite(int x, int y) {
x = getRoot(x);
y = getRoot(y);
if (x == y) {
return false;
}
if (size[x] >= size[y]) {
par[y] = x;
size[x] += size[y];
}
else {
par[x] = y;
size[y] += size[y];
}
return true;
}
};
int main() {
int N, M;
cin >> N >> M;
DSU dsu(N);
for (int i = 1; i <= M; ++i) {
int x, y, op;
cin >> op >> x >> y;
if (op == 1) {
dsu.unite(x, y);
}
else {
x = dsu.getRoot(x);
y = dsu.getRoot(y);
x == y ? cout << "DA\n" : cout << "NO\n";
}
}
}