Pagini recente » Cod sursa (job #1862914) | Stalpisori | Istoria paginii monthly-2014/runda-8/solutii | Cod sursa (job #472541) | Cod sursa (job #2076386)
#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
using namespace std;
class DisjointDataSets {
private:
vector<int> t, h;
int Root(int x) {
if (x == t[x]) {
return x;
}
t[x] = Root(t[x]);
return t[x];
}
public:
DisjointDataSets() = default;
DisjointDataSets(int n) {
h.assign(n + 1, 1);
t.assign(n + 1, 0);
for (int i = 1; i <= n; ++ i) {
t[i] = i;
}
}
void Unite(int x, int y) {
x = Root(x);
y = Root(y);
if (h[x] <= h[y]) {
t[x] = y;
if (h[x] == h[y]) {
++ h[y];
}
}
}
bool SameSet(int x, int y) {
return Root(x) == Root(y);
}
};
int main() {
ifstream cin("disjoint.in");
ofstream cout("disjoint.out");
int n, m;
cin >> n >> m;
DisjointDataSets d(n);
for (int i = 1; i <= m; ++ i) {
int type, x, y;
cin >> type >> x >> y;
if (type == 1) {
d.Unite(x, y);
} else {
cout << (d.SameSet(x, y) ? "DA" : "NU") << "\n";
}
}
return 0;
}