您的位置:首页 > 其它

我对并查集的了解及模板

2017-03-19 15:18 211 查看
并查集主要有两种操作 : 1 合并两个不想交的集合。 2 检索某元素属于哪个集合。

合并操作: 启发式合并

void Union(int x,int y)
{
int a=Find(x);
int b=Find(y);
if(a==b)
return ;
if(rank[a]<rank[b])
{
Father[b]=a;
}
else
{
if(rank[a]==rank[b]) rank[b]++;
Father[a]=b;
}
}
查找操作:路径压缩

非递归不会造成栈溢出
int find(int x)
{
int root=x;
while(father[root]>=0)
{
root=father[root];
}
while(root!=x)
{
int temp=father[x];
father[x]=root;
x=temp;
}
return root;
}

递归
int find(int x)
{
if(x!=father[x])
father[x]=find(father[x]);
return father[x];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: