Pagini recente » Cod sursa (job #971537) | Cod sursa (job #642001) | Cod sursa (job #3032453) | Cod sursa (job #2506940) | Cod sursa (job #2073926)
#include <fstream>
using namespace std;
ifstream in("disjoint.in");
ofstream out("disjoint.out");
int n, m, q, x, y;
struct tree{
int parent;
int depth;
}v[100001];
int find_root(int i){
int root = i, node = i, copy_i = i;
while (v[node].parent != root)
node = root = v[node].parent;
node = i;
while (v[node].parent != root){
copy_i = node;
node = v[node].parent;
v[copy_i].parent = root;
v[copy_i].depth = 0;
}
return root;
}
void union_trees(int i, int j){
int root_i = find_root(i);
int root_j = find_root(j);
if (root_i != root_j){
if (v[root_i].depth < v[root_j].depth)
v[root_i].parent = root_j;
if (v[root_j].depth < v[root_i].depth)
v[root_j].parent = root_i;
if (v[root_i].depth == v[root_j].depth){
v[root_j].parent = root_i;
v[root_j].depth += 1;
}
}
}
void querry(int i, int j){
int root_i = find_root(i);
int root_j = find_root(j);
if (root_i == root_j)
out << "DA" << '\n';
else
out << "NU" << '\n';
}
int main(){
in >> n >> m;
for (int i = 1; i <= n; ++ i){
v[i].parent = i;
v[i].depth = 0;
}
for (int i = 1; i <= m; ++ i){
in >> q >> x >> y;
if (q == 1)
union_trees(x, y);
else
querry(x, y);
}
return 0;
}