1 //并查集类 2 #include <cstdlib> 3 #include <iostream> 4 #include <vector> 5 6 7 using namespace std; 8 class Fmsets{ 9 vector<int> parent_; 10 11 protected: 12 int colapsing_find(int i){//折叠查找 并返回节点i的根 13 int rt=i; 14 for(;parent_[rt]>=0;rt=parent_[i]){} 15 for(int temp;rt!=i;i=temp){temp=parent_[i];parent_[i]=rt;} 16 return rt; 17 } 18 void ranked_merge(int i,int j){//按秩合并 19 if(parent_[i]<parent_[j]) std::swap(i,j); 20 if(parent_[i]==parent_[j]) --parent_[j]; 21 parent_[i]=j; 22 } 23 24 public: 25 Fmsets(int n):parent_(n,-1){} 26 int find(int i){return colapsing_find(i);} 27 void merge(int i,int j){ranked_merge(i,j);} 28 bool find_merge(int i,int j){ 29 i=find(i);j=find(j); 30 if(i==j) return false; 31 merge(i,j) return true; 32 } 33 }; 34 35 int main(int argc, char *argv[]) 36 { 37 38 39 system("PAUSE"); 40 return EXIT_SUCCESS; 41 }