并查集路径压缩
2015-08-05 16:33
232 查看
递归方法路径压缩:
int find(int x)
{
if(x!=father[x])
father[x]=find(father[x]);
return father[x];
}
上面代码可能会RE;建议用下面的代码:
int findset(int x)
{
int r = x;
while(father[r]!=r) ///查找跟节点
r = father[r]; ///找到根节点,用r记录
int i = x,j;
while(i != r) ///非递归路径压缩
{
j = father[i]; ///用j暂时存father[i]的父节点
father[i] = r; ///father[i]指向跟节点
i = j; ///i移到父节点
}
return r; ///返回根节点的值
}
int find(int x)
{
if(x!=father[x])
father[x]=find(father[x]);
return father[x];
}
上面代码可能会RE;建议用下面的代码:
int findset(int x)
{
int r = x;
while(father[r]!=r) ///查找跟节点
r = father[r]; ///找到根节点,用r记录
int i = x,j;
while(i != r) ///非递归路径压缩
{
j = father[i]; ///用j暂时存father[i]的父节点
father[i] = r; ///father[i]指向跟节点
i = j; ///i移到父节点
}
return r; ///返回根节点的值
}
相关文章推荐
- A signed resource has been added, modified, or deleted” when trying to debug an App on iPhone
- LCA最近公共祖先的离线算法(Tarjan)和在线算法(ST)
- H2 连接方式、简单使用
- GRFC (generic rf control)
- GUI编程:菜单的操作
- IOS学习笔记37——ViewController生命周期详解
- SAP IDOC开发
- discuz!安装遇到问题的解决方案
- 网页布局的例子
- 数据结构-----线性表
- XML常用函数http://blog.csdn.net/ly61baby/article/details/6458383
- hdu 2054 A == B ? (java)
- PHP关联数组的10个操作技巧
- Matrix Power Series(矩阵快速幂+求幂和)
- 10个加速Table Views开发的Tips
- 旋转字符串
- 一个批量安装文件夹下(包括子目录下)全部的Android apk文件批处理脚本
- Openjudge1288 The Rotation Game(dfs)
- Java游戏之碰撞检测
- webuploader