Pagini recente » Cod sursa (job #867376) | Cod sursa (job #77673) | Cod sursa (job #361521) | Cod sursa (job #409015) | Cod sursa (job #3197495)
#include <iostream>
#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]) {
swap(x, y);
}
par[x] = y;
size[y] += size[x];
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 << "NU\n";
}
}
}
//5 10
//2 5 5
//2 1 3
//1 1 2
//2 1 4
//2 3 4
//1 1 3
//2 2 4
//2 4 2
//1 4 1
//2 5 2