并查集 路径压缩

                一直不是很明白并查集路径压缩,总习惯一种写法

         一般的循环查找跟:

int find (int x){
    while (x != father[x]){
        x = father[x];
    }
    return x;
}

        递归查找:

int find (int x){
    if(x == father[x]){
        return x;
    }
    else{
        return find( father[x]);
    }
}

路径压缩的递归 :

int find(int x)  { //查找x元素所在的集合,回溯时压缩路径
if (x != father[x]){
        father[x] = find(father[x]);     //回溯时的压缩路径
    }         //从x结点搜索到祖先结点所经过的结点都指向该祖先结点
    return father[x];
}

路径压缩非递归:

int find(int x){
    int k, j, r;
    r = x;
    while(r != father[r]) {    //查找跟节点
            r = father[r];      //找到跟节点,用r记录下
    }     
    k = x;        
    while(k != r){            //非递归路径压缩操作
        j = father[k];         //用j暂存parent[k]的父节点
        father[k] = r;        //parent[x]指向跟节点
        k = j;                    //k移到父节点
    }
    return r;         //返回根节点的值            
}


猜你喜欢

转载自blog.csdn.net/weixin_41190227/article/details/79516919
今日推荐