并查集路径压缩优化 UnionFind PathCompression(C++)
2024-08-27 16:54:26
/*
* UnionFind.h
* 有两种实现方式,QuickFind和QuickUnion
* QuickFind:
* 查找O(1)
* 合并O(n)
* QuickUnion:(建议使用)
* 查找O(logn)可优化至O(a(n)),a(n)<5
* 合并O(logn)可优化至O(a(n)),a(n)<5
* Created on: 2020年2月13日
* Author: LuYonglei
*/ //由于QuickFind平均时间复杂度不理想,所以本文件只用QuickUnion来实现
//本文件基于rank实现优化
//在原有基础上实现路径压缩
#ifndef SRC_UNIONFIND_H_
#define SRC_UNIONFIND_H_
#include <assert.h>
#include <stack>
#define DEFAULT_CAPACITY 10
using namespace std; class UnionFind {
public:
UnionFind(int capacity) :
capacity_(capacity > ? capacity : DEFAULT_CAPACITY), parents(
new int[capacity > ? capacity : DEFAULT_CAPACITY]), ranks(
new int[capacity > ? capacity : DEFAULT_CAPACITY]) {
//初始化构造函数
for (int i = ; i < capacity_; i++) {
parents[i] = i;
ranks[i] = ; //以i为根节点的树的高度
}
} ~UnionFind() {
//析构函数
delete[] parents;
delete[] ranks;
} #if 0
//递归实现路径压缩
int findParent(int value) {
assert(value < capacity_ && value >= );
if (parents[value] != value) {
parents[value] = findParent(parents[value]);
}
return parents[value];
}
#elif 0
//迭代实现路径压缩1
int findParent(int value) {
assert(value < capacity_ && value >= );
stack<int> s;
while (value != parents[value]) {
s.push(value);
value = parents[value];
}
int preIndex = ;
while (s.size() != ) {
preIndex = s.top();
parents[preIndex] = value;
s.pop();
}
return value;
} #else
//迭代实现路径压缩2
int findParent(int value) {
assert(value < capacity_ && value >= );
int begin = value;
while (value != parents[value]) {
value = parents[value];
}
int tmpBegin = ;
while (begin != value) {
tmpBegin = parents[begin];
parents[begin] = value;
begin = tmpBegin;
}
return value;
} #endif void unionValue(int leftValue, int rightValue) {
//统一实现左边跟随右边
int leftParent = findParent(leftValue);
int rightParent = findParent(rightValue);
if (leftParent == rightParent)
return;
if (ranks[leftParent] < ranks[rightParent]) {
parents[leftParent] = rightParent;
} else if (ranks[rightParent] > ranks[leftParent]) {
parents[rightParent] = leftParent;
} else {
parents[leftParent] = rightParent;
ranks[rightParent] += ;
}
} bool isSame(int leftValue, int rightValue) {
return findParent(leftValue) == findParent(rightValue);
} private:
int capacity_;
int *parents;
int *ranks;
}; #endif /* SRC_UNIONFIND_H_ */
最新文章
- 构造函数this和base的区别
- 解决:eclipse 非正常关闭,导致无法正常启动
- DQL、DML、DDL、DCL的概念与区别
- HTML meta viewport属性说明(mark)
- Thinking in Java——笔记(6)
- Eclipse Java 调试基本技巧
- Android之 -WebView实现离线缓存阅读
- msp
- neural style论文解读
- [置顶] 正则表达式应用:匹配email地址
- SQL Server 的锁定和阻塞
- appiun滑动的简单封装
- React Native 断点调试 跨域资源加载出错问题的原因分析
- Linux实战教学笔记49:Zabbix监控平台3.2.4(一)搭建部署与概述
- spring boot(三) 集成mybatis
- 搜素表脚本.vbs
- 小程序webview应用实践
- Linux vsftd配置文件
- python 的zip 函数小例子
- bzoj 2460 [BeiJing2011]元素 (线性基)