c++并查集優(yōu)化(基于size和rank)
基于size的優(yōu)化是指:當(dāng)我們在指定由誰連接誰的時(shí)候,size數(shù)組維護(hù)的是當(dāng)前集合中元素的個(gè)數(shù),讓數(shù)據(jù)少的指向數(shù)據(jù)多的集合中
基于rank的優(yōu)化是指:當(dāng)我們在指定由誰連接誰的時(shí)候,rank數(shù)組維護(hù)的是當(dāng)前集合中樹的高度,讓高度低的集合指向高度高的集合
運(yùn)行時(shí)間是差不多的:

基于size的代碼: UnionFind3.h
#ifndef UNION_FIND3_H_
#define UNION_FIND3_H_
#include<iostream>
#include<cassert>
namespace UF3
{
class UnionFind
{
private:
int* parent;
int* sz; //sz[i]就表示以i為根的集合中元素的個(gè)數(shù)
int count;
public:
UnionFind(int count)
{
this->count = count;
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 < count && p >= 0);
while( p != parent[p]) //這個(gè)是寫到find里面的
{
p = parent[p];
}
return p;
}
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];
}
}
bool isConnected(int p , int q)
{
return find(p) == find(q);
}
};
};
#endif
基于rank的代碼: UnionFind4.h
#ifndef UNION_FIND4_H_
#define UNION_FIND4_H_
#include<iostream>
#include<cassert>
namespace UF4
{
class UnionFind
{
private:
int* parent;
int* rank; //rank[i]就表示以i為根的集合的層數(shù)
int count;
public:
UnionFind(int count)
{
this->count = count;
parent = new int[count];
rank = new int[count];
for(int i = 0 ; i < count ; i++)
{
parent[i] = i;
rank[i] = 1;
}
}
~UnionFind()
{
delete [] parent;
delete [] rank;
}
int find(int p)
{
assert(p < count && p >= 0);
while( p != parent[p]) //這個(gè)是寫到find里面的
{
p = parent[p];
}
return p;
}
void unionElements(int p , int q)
{
int pRoot = find(p);
int qRoot = find(q);
if( pRoot == qRoot)
return;
if(rank[pRoot] < rank[qRoot])
{
parent[pRoot] = qRoot;
}
else if( rank[pRoot] > rank[qRoot] )
{
parent[qRoot] = pRoot;
}
else
{
parent[pRoot] = qRoot; //這里誰指向誰無所謂
rank[qRoot] ++;
}
}
bool isConnected(int p , int q)
{
return find(p) == find(q);
}
};
};
#endif
剩下的頭文件和main文件在上一個(gè)并查集的博客中有,就不再粘貼出來了
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
VC++中HTControl控件類之CHTRichEdit富文本編輯控件實(shí)例
這篇文章主要介紹了VC++中HTControl控件類之CHTRichEdit富文本編輯控件,是一個(gè)比較實(shí)用的功能,需要的朋友可以參考下2014-08-08
Qt QStandardItemModel用法小結(jié)
詳解C語言中sizeof如何在自定義函數(shù)中正常工作
C++深入講解類與對(duì)象之OOP面向?qū)ο缶幊膛c封裝
C++下如何將TensorFlow模型封裝成DLL供C#調(diào)用

