Pagini recente » Cod sursa (job #2550961) | Cod sursa (job #321697) | Cod sursa (job #2675933) | Cod sursa (job #59246) | Cod sursa (job #954366)
Cod sursa(job #954366)
#include <cstdio>
#include <cassert>
#include <algorithm>
#include <vector>
using namespace std;
class DisjointSets {
public:
DisjointSets() {
size = 0;
father = vector<int>();
}
DisjointSets(const int size) {
this->size = size;
father = vector<int>(size, NIL);
rank = vector<int>(size, 1);
}
int Find(const int x) {
if (father[x] == NIL)
return x;
return father[x] = Find(father[x]);
}
bool Merge(int x, int y) {
x = Find(x); y = Find(y);
if (x == y)
return false;
if (rank[x] < rank[y])
swap(x, y);
father[y] = x;
rank[x] = max(rank[x], rank[y] + 1);
return true;
}
private:
static const int NIL = -1;
int size;
vector<int> father, rank;
};
int main() {
assert(freopen("disjoint.in", "r", stdin));
assert(freopen("disjoint.out", "w", stdout));
int N, M; assert(scanf("%d %d", &N, &M) == 2);
DisjointSets sets = DisjointSets(N);
for (; M > 0; --M) {
int type, x, y;
assert(scanf("%d %d %d", &type, &x, &y) == 3);
--x; --y;
if (type == 1)
assert(sets.Merge(x, y));
else
printf("%s\n", (sets.Find(x) == sets.Find(y) ? "DA" : "NU"));
}
return 0;
}