我对并查集的了解及模板
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];
}
合并操作: 启发式合并
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];
}
相关文章推荐
- 【数据结构】【并查集模板】
- 【翻译】最新版CodeSmith3.2(.net2.0)教程之三:了解你要创建一个什么模板
- 并查集模板
- HDU-1213-How Many Tables(并查集模板题)
- 并查集模板代码实现(非递归)
- HDU1213 并查集模板
- POJ 1611 The Suspects(并查集模板)
- HDU 1232:畅通工程(并查集模板)
- 算法模板——并查集 2(支持快速即时查询本连通块内容,纯原创!)
- 【模板】并查集
- 【模板】并查集 两种路径压缩写法
- Hdu 1232 畅通工程(并查集模板题)
- C++-并查集模板
- 并查集模板
- HDU 1213 How Many Tables(并查集模板)
- 并查集 模板
- caioj1092 并查集模板
- 1poj2524(套模板并查集)
- 并查集(Union-Find Set)模板
- [模板] - 略优化的并查集