Disjoint Set, coprime set

Disjoint Set, (an element does not belong to multiple sets at the same time). Here, the forest structure is used to represent the collection set, the tree represents the collection, the root element is the representative element, and the number of records in the rank array is high.

FIndSet(x) finds the representative element of the containing element-aware set,

In the tree, find x, return the representative element, compress the path, and point all nodes from x to the root to the root node. Reduce search time.

unite(x,y) merges the trees x,y.

Add the low tree height to the tree high set, so that the low height set root node points to the high height root node.

#include<iostream>
#include<vector>
using namespace std;
class DisjointSet{                                                             //森林结构
public:
vector<int> rank,p;
DisjointSet() {} //Constructor
DisjointSet(int size) {
rank.resize(size,0);
p.resize(size,0);
for (int i=0;i<size;i++) makeSet(i);            //建立树
}
void makeSet(int x) {
p[x]=x;
rank[x]=0;
}
bool same(int x,int y) {
return findSet(x)==findSet(y);
}
void unite(int x,int y) {
link(findSet(x),findSet(y));                            
}
void link(int x,int y) {
if (rank[x]>rank[y]) { //Here, the following table of array is used to represent the node or element, and the number in the array is the representative element
p[y]=x;
}
else {
p[x]=y;
if (rank[x]==rank[y]) {
rank[y]++;
}
}
}
int findSet(int x) {
if (x!=p[x]) { //When the height is zero, the representative element is the element
p[x]=findSet(p[x]); //p[x] is the subscript representing the element?
}
return p[x];
}
};
int main() {
int n,a,b,q;
int t;
cin>>n>>q;
DisjointSet ds=DisjointSet(n);
for (int i=0;i<q;i++) {
cin>>t>>a>>b;
if (t==0) ds.unite(a,b);
else if (t==1) {
if (ds.same(a,b)) cout <<1<<endl;
else cout<<0<<endl;
}
}
return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325405699&siteId=291194637