并查集学习笔记

 并查集(Union-Find Sets),字面意思理解——合并,查找。给出一个集合,将其合并后用一个点代替一个集合的元素。

例如:

1    2

2    3

4    3

合并后就是

        2

    /        \

1             3

                 \

                     4

主要操作:

1、查找。

2、合并。

查找方法见http://www.cnblogs.com/vongang/archive/2011/07/31/2122763.html

合并实现方法如下:

void Union(int root1, int root2){
     int x = FindSet(root1), y = FindSet(root2);
     if( x == y ) return ;
     if( rank[x] > rank[y] ) parent[y] = x;
     else{
         parent[x] = y;
         if( rank[x] == rank[y] ) ++rank[y];
     }
}
void Initi(void){
     memset(rank, 0, sizeof(rank));
     for( int i=0; i < MAXSIZE; ++i ) parent[i] = i;
}
原文地址:https://www.cnblogs.com/timeship/p/2622317.html