并查集

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

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

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

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

\(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;//记得要初始化
posted @ 2020-01-22 19:50  lhm_liu  阅读(150)  评论(0编辑  收藏  举报