/*
* 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_ */

最新文章

  1. 在IIS EXPRESS下运行一个visual studio 项目,跳转到另一个项目的解决方案。
  2. 【python】dict。字典
  3. matlab查找回车字符
  4. C程序设计语言练习题1-3
  5. 微软IE11浏览器的7大变化
  6. lua 序列化函数
  7. shell的case语句
  8. Asp.Net Core 轻松学-实现跨平台的自定义Json数据包
  9. 四、Java多人博客系统-2.0版本
  10. 【移动端】移动端字体单位font-size选择px还是rem
  11. [C]gcc编译器的一些常用语法
  12. Core 中 Filter 中相关处理
  13. JavaMail实现邮箱之间发送邮件功能
  14. ios模拟器已安装但xcode无法显示
  15. PHP中oop面向对象基础知识(一)
  16. windows控制台程序——关于UNICODE字符的总结(转)
  17. Android GUI之Window、WindowManager
  18. Nginx与Tomcat实现请求动态数据与请求静态资源的分离
  19. (转)java +libsvm 安装与测试:
  20. Java RSA加密算法生成公钥和私钥

热门文章

  1. Your idea evaluation has expired. Your session will be limited to 30 minutes
  2. 大二网课ing学习周记
  3. CSS中before、after伪类选择器的巧用
  4. shell中expect免交互
  5. 【redis】spring boot利用redis的Keyspace Notifications实现消息通知
  6. 小白的linux笔记2:关于进程的基本操作
  7. 双向队列 SDUT 1466
  8. 论文阅读笔记(十四)【AAAI2020】:Appearance and Motion Enhancement for Video-based Person Re-identification
  9. node种buffer对象数组 深拷贝浅拷贝问题
  10. mssql格式化工具——SQL PRETTY PRINTER