#include <iostream>
usingnamespacestd;
classUF {
//cnt is the number of disjoint sets.
//id is an array that records distinct identity of each set,when two sets are merged ,their id will be same.
//sz is an array that records the child number of each set including the set self.
int*id, cnt, *sz;
public:
// Create an empty union find data structure with N isolated sets.
UF(intN) {
cnt = N;
id =newint[N];
sz =newint[N];
for(inti = 0; i<N; i++) {
id[i] = i;
sz[i] = 1;
}
}
~UF() {
delete[] id;
delete[] sz;
}
// Return the id of component corresponding to object p.
intfind(intp) {
if(p != id[p]){
id[p] = find(id[p]);
}
returnid[p];
}
// Replace sets containing x and y with their union.
voidmerge(intx,inty) {
inti = find(x);
intj = find(y);
if(i == j)return;
// make smaller root point to larger one
if(sz[i] < sz[j]) {
id[i] = j;
sz[j] += sz[i];
}
else{
id[j] = i;
sz[i] += sz[j];
}
cnt--;
}
// Are objects x and y in the same set?
boolconnected(intx,inty) {
returnfind(x) == find(y);
}
// Return the number of disjoint sets.
intcount() {
returncnt;
}
};
voidmain(){
UF test(5);
test.merge(2, 3);
test.merge(3, 4);
cout << test.find(4);
cout << test.count();
}
|