并查集

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

 

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

 

相关文章:

  • 2021-11-13
  • 2021-06-04
  • 2021-11-09
猜你喜欢
  • 2022-12-23
  • 2021-11-01
  • 2021-10-10
  • 2022-02-12
  • 2022-01-06
相关资源
相似解决方案