首页 > 其他 > 详细

并查集

时间:2020-01-22 20:08:54      阅读:57      评论:0      收藏:0      [点我收藏+]

并查集为森林的结构。有多棵多叉树,每个树的根结点定义为这棵树中元素的代表结点。

用于查询两个点是否在同一集合内,以及合并两个集合。

并查集妙用,如白雪皑皑求和并替换

带有偏移量的并查集,如银河英雄传说食物链

\(code\)

int find(int x)
{
    return fa[x]==x?fa[x]:fa[x]=find(fa[x]);//路径压缩
}
void merge(int x,int y)
{
    int rootx=find(x),rooty=find(y);
    if(rootx==rooty) return;
    if(de[rootx]<de[rooty]) swap(rootx,rooty);//按秩合并
    fa[rooty]=rootx;
    de[rootx]=max(de[rootx],de[rooty]+1);
}

......

for(int i=1;i<=n;++i) fa[i]=i;//记得要初始化

并查集

原文:https://www.cnblogs.com/lhm-/p/12229425.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!