Pagini recente » Cod sursa (job #3267191) | Cod sursa (job #3265527) | Cod sursa (job #2949959) | Cod sursa (job #2413221) | Cod sursa (job #3206826)
#include <fstream>
using namespace std;
const int NMAX = 100000;
int father[NMAX + 1];
int depth[NMAX + 1];
ifstream fin("disjoint.in");
ofstream fout("disjoint.out");
/*
int root(int x) {
while (x != father[x])
x = father[x];
return x;
}
*/
int root(int x) {
if (x == father[x])
return x;
int r = root(father[x]);
father[x] = r;
return r;
}
void unite(int a, int b) {
int x = root(a);
int y = root(b);
if (x == y) {
return;
}
if (depth[x] < depth[y])
father[x] = y;
else if (depth[x] > depth[y])
father[y] = x;
else {
father[x] = y;
depth[y]++;
}
}
bool query(int a, int b) {
int x = root(a);
int y = root(b);
return x == y;
}
int main() {
int n, t, x, y, q;
fin >> n >> q;
for (int i = 1; i <= n; i++) {
father[i] = i;
depth[i] = 1;
}
for (int i = 1; i <= q; i++) {
fin >> t >> x >> y;
if (t == 1) { // Unite nodes x and y
unite(x, y);
} else {
if (query(x, y))
fout << "DA\n";
else
fout << "NU\n";
}
}
return 0;
}