并查集模板

并查集

并查集是数据结构中的一个重要算法,可以管理元素分组,并查集由三部分构成:初始化,找父节点,合并结点,直接来看并查集的模板:

 

const int max_size=1000;

int pre[max_size];
void init_set(int count){
    for (int i = 1; i <= count; i++)
    {
        pre[i]=i;
    }
}
int find_set(int x){
    return x==pre[x]?x:find_set(pre[x]);
}
void union_set(int x,int y){
    x =find_set(x);
    y=find_set(y);
    if(x!=y) pre[x]=pre[y];
}

 

合并优化:将高度较小的集合并到较大的集合上

const int max_size=1000;

int pre[max_size],height[max_size];
void init_set(int count){
    for (int i = 1; i <= count; i++)
    {
        pre[i]=i;
        height[i]=0;
    }
}
int find_set(int x){
    return x==pre[x]?x:find_set(pre[x]);
}
void union_set(int x,int y){
    x =find_set(x);
    y=find_set(y);
    if (height[x]==height[y])
    {
       height[x]=height[x]+1;
       pre[y]=x;
    }else
    {
        if (height[x]<height[y])
            pre[x]=y;
        else
            pre[y]=x;
    }
}

路径压缩:

int find_set(int x){
    if (x!=pre[x])
    {
        pre[x]=find_set(pre[x]);
    }
    return pre[x];
}

 

posted @ 2020-09-12 08:32  多发Paper哈  阅读(103)  评论(0编辑  收藏  举报
Live2D