void ufs_initialize(int n, int parent[]){
/* initialize set -1 */
for(int i=0; i<n; ++i)
parent[i]
= -1;
}

void ufs_union(int i, int j, int parent[]){
/* union the sets with roots i and j, i != j, using the weighting rule. */
if(parent[i] > parent[j]){
parent[j] += parent[i];
parent[i]
= j;
}
else{
parent[i] += parent[j];
parent[j]
= i;
}
}

int ufs_find(int i, int parent[]){
/* find the root of the tree containing element i.
Use the collapsing rule to collapse all nodes from i to root
*/
int root, trail, lead;
for(root = i; parent[root]>=0; root=parent[root]) ;
//collapse(压缩)
trail = i;
while(trail != root){
lead
= parent[trail];
parent[trail]
= root;
trail
= lead;
}
return root;
}

 

 

posted on 2010-07-10 23:33  yongmou-  阅读(210)  评论(0编辑  收藏  举报