您的位置:首页 > 其它

并查集路径压缩

2015-10-15 09:01 260 查看
//非递归压缩路径
int findx(int x){
int root = x;
// 先找到根节点.
while(root != parent[root])
root = parent[root];
while(x != root){
int p = parent[x];
parent[x] = root;  // 将x指向根节点.
x = p; // 移到x原来的父节点继续进行压缩.
}
return root;
}

//回溯路径时压缩, 可能会造成堆栈溢出, 建议用上一种.
int findx(int x){
if(x!=parent[x]){
parent[x] = findx(parent[x]);
}
return parent[x];
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: