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;
}