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

最新文章

  1. 构造函数this和base的区别
  2. 解决:eclipse 非正常关闭,导致无法正常启动
  3. DQL、DML、DDL、DCL的概念与区别
  4. HTML meta viewport属性说明(mark)
  5. Thinking in Java——笔记(6)
  6. Eclipse Java 调试基本技巧
  7. Android之 -WebView实现离线缓存阅读
  8. msp
  9. neural style论文解读
  10. [置顶] 正则表达式应用:匹配email地址
  11. SQL Server 的锁定和阻塞
  12. appiun滑动的简单封装
  13. React Native 断点调试 跨域资源加载出错问题的原因分析
  14. Linux实战教学笔记49:Zabbix监控平台3.2.4(一)搭建部署与概述
  15. spring boot(三) 集成mybatis
  16. 搜素表脚本.vbs
  17. 小程序webview应用实践
  18. Linux vsftd配置文件
  19. python 的zip 函数小例子
  20. bzoj 2460 [BeiJing2011]元素 (线性基)

热门文章

  1. 蓝眼睛与红眼睛(The blue-eyed islanders puzzle)
  2. JAVA JDBC 连接数据库
  3. AMBA简介
  4. Qt获取当前屏幕大小
  5. [51nod 1256] 乘法逆元 - exgcd
  6. KindEditor配置和使用
  7. vue-cli莫名其妙的警告
  8. JN_0010:谷歌浏览器启动安全模式,直接打开H5项目
  9. MySQL 8 服务器组件
  10. Android之活动Activity用法