資料結構與演算法C 之並查集 基於rank的優化

2021-09-01 09:06:20 字數 2132 閱讀 7978

根據根節點數目少的指向根節點數目多的,4的根節點數目為3,2的根節點數目為6,那麼需要將4的根節點8指向2的根節點7,但是這樣樹的高度變為4

而如果將2的根節點7指向4的根節點8,那麼這樣樹的高度變為3,因此需要根據樹的高度來判斷誰指向誰

根據樹的高度判斷指向,稱為基於rank的優化

程式實現為

#include

#include

#include

"unionfindtesthelper.h"

using namespace std;

intmain()

"unionfindtesthelper.h"定義為

#include

#include

#include

//rand()º¯êý

#include

"unionfind1.h"

#include

"unionfind2.h"

#include

"unionfind3.h"

#include

"unionfind4.h"

using namespace std;

namespace unionfindtesthelper

for(

int i =

0; i < n; i++

) time_t endtime =

clock()

; cout<<

"uf3, "

<<

2*n<<

" ops, "

<<

double

(endtime-starttime)

/clocks_per_sec<<

" s"

<

}void

testuf4

(int n)

for(

int i =

0; i < n; i++

) time_t endtime =

clock()

; cout<<

"uf4, "

<<

2*n<<

" ops, "

<<

double

(endtime-starttime)

/clocks_per_sec<<

" s"

<

}}

本篇部落格實現的基於rank的優化"unionfind4.h"定義為

#include

#include

using namespace std;

namespace uf4 }~

unionfind()

intfind

(int p)

bool isconnected

(int p,

int q)

void

unionelements

(int p,

int q)

else

if(rank[proot]

> rank[qroot]

)else}}

;}

"unionfind3.h"定義見上篇部落格

輸出為

可以看出基於rank的優化並沒有比上乙個實現速度快,這是因為碰到需要rank的情況並不多見,而且甚至有時基於rank的優化還要比上乙個實現要慢,但是基於rank的優化可以處理一些極端的情況。

資料結構與演算法之並查集

並查集結構可以用於 1 檢查兩個元素是否屬於同乙個集合 比如對於圖1這個例子來說,如果我們想要檢查節點d和節點e是否屬於同乙個集合,可以這樣操作 d節點往上找其父節點,一直往上找,直到某個節點的父節點是其本身,此時停止 找到了節點a e節點也按照相同的步驟往上找其父節點,找到節點a 如果這兩個節點往...

資料結構與演算法之並查集

並查集 union find 是一種高效的資料結構,主要的操作有 為方便敘述,把所有元素視作點,元素之間的關係視作線,存在聯絡便存在關係 需要注意的是,這裡的關係應當是1.自反的,2.對稱的,3.傳遞的 所謂合併,便是將兩個點之間 畫 一條線。又上邊的定義不難理解相連的若干點之間互相存在關係,這樣我...

演算法基礎之資料結構 並查集

題目 合併計算 一共有 n 個數,編號是 1 n,最開始每個數各自在乙個集合中。現在要進行 m 個操作,操作共有兩種 m a b,將編號為 a 和 b 的兩個數所在的集合合併,如果兩個數已經在同乙個集合中,則忽略這個操作 q a b,詢問編號為 a 和 b 的兩個數是否在同乙個集合中 輸入格式 第一...