上篇中实现的union操作中合并两个元素是无序的,一般将第一个元素指向第二个元素,如下图中,是将4的根节点指向9,但是这样造成树总的高度为4,如果将9指向4的话,树的高度为3,树的高度减少后会很节省后面的查找花费的时间,因此需要先判断一下两个节点的根节点的数目,选择根节点数目少的节点指向根节点数目多的节点
下面是程序实现
#include <iostream>
#include <cassert>
#include "UnionFindTestHelper.h"
using namespace std;
int main()
{
int n = 100000;
UnionFindTestHelper::testUF1(n);
UnionFindTestHelper::testUF2(n);
UnionFindTestHelper::testUF3(n);
return 0;
}
"UnionFindTestHelper.h"定义为
//UnionFindTestHelper.h
#include <iostream>
#include <ctime>
#include <cstdlib> //rand()º¯Êý
#include "UnionFind1.h"
#include "UnionFind2.h"
#include "UnionFind3.h"
using namespace std;
namespace UnionFindTestHelper{
void testUF1(int n){
srand(time(NULL));
UF1::UnionFind uf = UF1::UnionFind(n);
time_t startTime = clock();
for(int i = 0; i < n; i++){
int a = rand()%n;
int b = rand()%n;
uf.unionElements(a, b);
}
for(int i = 0; i < n; i++){
int a = rand()%n;
int b = rand()%n;
uf.isConnected(a, b);
}
time_t endTime = clock();
cout<<"UF1, "<<2*n<<" ops, "<<double(endTime-startTime)/CLOCKS_PER_SEC<<" s"<<endl;
}
void testUF2(int n){
srand(time(NULL));
UF2::UnionFind uf = UF2::UnionFind(n);
time_t startTime = clock();
for(int i = 0; i < n; i++){
int a = rand()%n;
int b = rand()%n;
uf.unionElements(a, b);
}
for(int i = 0; i < n; i++){
int a = rand()%n;
int b = rand()%n;
uf.isConnected(a, b);
}
time_t endTime = clock();
cout<<"UF2, "<<2*n<<" ops, "<<double(endTime-startTime)/CLOCKS_PER_SEC<<" s"<<endl;
}
void testUF3(int n){
srand(time(NULL));
UF3::UnionFind uf = UF3::UnionFind(n);
time_t startTime = clock();
for(int i = 0; i < n; i++){
int a = rand()%n;
int b = rand()%n;
uf.unionElements(a, b);
}
for(int i = 0; i < n; i++){
int a = rand()%n;
int b = rand()%n;
uf.isConnected(a, b);
}
time_t endTime = clock();
cout<<"UF3, "<<2*n<<" ops, "<<double(endTime-startTime)/CLOCKS_PER_SEC<<" s"<<endl;
}
}
使用本篇博客实现的并查集UnionFind3.h定义为
//UnionFind3.h
#include <iostream>
#include <cassert>
using namespace std;
namespace UF3 {
class UnionFind {
private:
int *parent;
int *sz;
int count;
public:
UnionFind(int n){
count = n;
parent = new int[count];
sz = new int[count];
for(int i = 0; i < count; i++){
parent[i] = i;
sz[i] = 1;
}
}
~UnionFind(){
delete[] parent;
delete[] sz;
}
int find( int p){
assert( p >= 0 && p < count );
while(p != parent[p])
p = parent[p];
return p;
}
bool isConnected(int p, int q){
return find(p) == find(q);
}
void unionElements(int p, int q){
int pRoot = find(p);
int qRoot = find(q);
if ( pRoot == qRoot )
return;
if (sz[pRoot] < sz[qRoot]){
parent[pRoot] = qRoot;
sz[qRoot] += sz[pRoot];
}
else{
parent[qRoot] = pRoot;
sz[pRoot] += sz[qRoot];
}
}
};
}
"UnionFind1.h"和"UnionFind2.h"的定义见上篇博客
输出为
可以看出,20万次操作 优化后的并查集值花费了0.014秒