并查集和带权并查集
2016-08-17 09:06
288 查看
并查集
并查集是一个很高效算法,理解起来也很简单,写起来更简单。①fat[i] = i;
②找到一个点的祖先
int findfat(int x)
{
if(fat[x] == x) return x;
return findfat(fat[x]);
}
③二中的方法肯定不好,因为如果数据比较极端,那么并查集就退化成一个链了
如果加入了路径压缩,并查集这个算法就更高效了。
int findfat(int x)//递归写法
{
if(fat[x] == x) return x;
fat[x]=findfat(fat[x]);
return findfat(fat[x]);
}
int findfat(int x)//非递归写法 更好,因为不会RE { int root=x; while(root != fat[root])//先要找到根节点r { root=fat[root]; } int y=x; while(y!=root) { int fath=fat[y]; fat[y]=root; y=fath; } return r; }④合并
void join(int x,int y)
{
int fatx=findfat(x),faty=findfat(y);
if(fatx != faty)
{
fat[fatx]=faty;
}
}
带权并查集
带权值的并查集只不过是在并查集中加入了一个value[ ]数组value[ ]可以记录很多种东西,不一定是类似距离这种东西,也可以是相对于根节点的状态
加入了权值,函数应该有一些改变
①找到一个点的祖先
int findfat(int x) { if(fat[x] == x) return x; int tmp=fat[x]; fat[x]=findfat(fat[x]); //在此处修改val比如: value[x]=value[tmp]+1; return fat[x]; }
差不多就这样了……
相关文章推荐
- HDU 1272 并查集
- POJ 2236 A - Wireless Network[kuangbin带你飞]专题五 并查集
- nyoj 1022 合纵连横 经典并查集
- TOJ 1840 POJ 1127 HDU 1102 Jack Straws / 线段相交 + 并查集
- poj-1611-The Suspects(并查集)
- POJ - 2236 并查集
- 数据结构之并查集(Java版本)
- HDU 5458 Stability(树链剖分 + 并查集)
- POJ - 1456 贪心+并查集
- poj 1611 The Suspects(简单并查集)
- 算法:程序设计之并查集
- HDU 1213 How Many Tables 并查集
- 并查集
- 算法学习 并查集(笔试题目:找同伙)
- poj 2912 Rochambeau(带权并查集)(枚举)
- (step5.1.6)hdu 1272(小希的迷宫——并查集)
- 并查集 - 1611 The Suspects
- 算法基础篇(9)------并查集
- hdu 4619 Warm up 2(并查集)
- POJ 2524 Ubiquitous Religions (并查集)