Pagini recente » Cod sursa (job #213080) | Cod sursa (job #2487480) | Cod sursa (job #379737) | Cod sursa (job #2106189) | Cod sursa (job #1256559)
#include <iostream>
#include <memory.h>
using namespace std;
class disjointSet{
private:
const static int limit = 100001;
int entries;
int group[limit];
int depth[limit];
int find_root(int x){
if(group[x] == x)
return x;
return find_root(group[x]);
}
public:
disjointSet(int n){
entries = n;
for(int i = 1 ;i <= n; i++){
group[i] = i;
depth[i] = 0;
}
}
void unite(int x,int y){
int xRoot = find_root(x);
int yRoot = find_root(y);
if(depth[xRoot] < depth[yRoot])
group[xRoot] = yRoot;
else if (depth[xRoot] > depth[yRoot]){
group[yRoot] = xRoot;
}else{
group[xRoot] = yRoot;
depth[yRoot] ++;
}
}
bool connected(int x,int y){
return find_root(x)==find_root(y);
}
void print_group(){
for(int i =1;i <= entries; i++){
cout << group[i] << " ";
}
cout << endl;
}
};
int main(){
freopen("disjoint.in","r",stdin);
freopen("disjoint.out","w",stdout);
int n,m;
cin >> n >> m;
disjointSet disjoint_set(n);
for(int i = 0; i < m ; i++){
int c,x,y;
cin >> c >> x >> y;
if(c == 2){
if(disjoint_set.connected(x,y))
cout << "DA" << endl;
else
cout << "NU" << endl;
}
else{
disjoint_set.unite(x,y);
}
// disjoint_set.print_group();
}
return 0;
}