并查集路径减半优化 UnionFind PathHalving (C++)
2024-10-08 09:46:13
/*
* 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>
#define DEFAULT_CAPACITY 10 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;
} int findParent(int value) {
assert(value < capacity_ && value >= );
while (value != parents[value]) {
parents[value] = parents[parents[value]];
value = parents[value];
}
return value;
} 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_ */
最新文章
- 在IIS EXPRESS下运行一个visual studio 项目,跳转到另一个项目的解决方案。
- 【python】dict。字典
- matlab查找回车字符
- C程序设计语言练习题1-3
- 微软IE11浏览器的7大变化
- lua 序列化函数
- shell的case语句
- Asp.Net Core 轻松学-实现跨平台的自定义Json数据包
- 四、Java多人博客系统-2.0版本
- 【移动端】移动端字体单位font-size选择px还是rem
- [C]gcc编译器的一些常用语法
- Core 中 Filter 中相关处理
- JavaMail实现邮箱之间发送邮件功能
- ios模拟器已安装但xcode无法显示
- PHP中oop面向对象基础知识(一)
- windows控制台程序——关于UNICODE字符的总结(转)
- Android GUI之Window、WindowManager
- Nginx与Tomcat实现请求动态数据与请求静态资源的分离
- (转)java +libsvm 安装与测试:
- Java RSA加密算法生成公钥和私钥
热门文章
- Your idea evaluation has expired. Your session will be limited to 30 minutes
- 大二网课ing学习周记
- CSS中before、after伪类选择器的巧用
- shell中expect免交互
- 【redis】spring boot利用redis的Keyspace Notifications实现消息通知
- 小白的linux笔记2:关于进程的基本操作
- 双向队列 SDUT 1466
- 论文阅读笔记(十四)【AAAI2020】:Appearance and Motion Enhancement for Video-based Person Re-identification
- node种buffer对象数组 深拷贝浅拷贝问题
- mssql格式化工具——SQL PRETTY PRINTER