溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

C++是如何實現(xiàn)并查集的

發(fā)布時間:2020-07-06 10:24:35 來源:億速云 閱讀:167 作者:清晨 欄目:開發(fā)技術(shù)

小編給大家分享一下C++是如何實現(xiàn)并查集的,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!

#include <iostream>
#include <vector>
#include <cassert>

using namespace std;

class UnionFind{
private:
  vector<int> parent;
  int count;
  //優(yōu)化,記錄p和q所在組的深度,在合并時將深度小的結(jié)點的根指向深度大的結(jié)點的根
  vector<int> rank; 

public:
  UnionFind(int count){
    parent.resize(count);
    rank.resize(count);
    this->count = count;
    for(int i = 0; i < count; ++i){
      parent[i] = i;
      rank[i] = 1;
    }
  }
  ~UnionFind(){
    parent.clear();
    rank.clear();
  }
  //路徑壓縮
  int find(int p){
    assert(p >= 0 && p < count);
    if(p != parent[p])
      parent[p] = find(parent[p]);
    return parent[p];
  }
  bool isConnected(int p, int q){
    return find(p) == find(q);
  }
  void unionElement(int p, int q){
    int pRoot = find(p), qRoot = find(q);
    if(pRoot == qRoot)
      return;
    if(rank[pRoot] < rank[qRoot])
      parent[pRoot] = qRoot;
    else if(rank[qRoot] < rank[pRoot])
      parent[qRoot] = pRoot;
    else{
      //兩者的rank相等
      parent[pRoot] = qRoot;
      rank[qRoot] += 1;
    }
  }
};

小編再補充一段代碼,之前收藏的一段代碼:

#include <iostream>

using namespace std;
class UF  {
 //cnt is the number of disjoint sets.
 //id is an array that records distinct identity of each set,when two sets are merged ,their id will be same.
 //sz is an array that records the child number of each set including the set self.
 int *id, cnt, *sz;
public:
 // Create an empty union find data structure with N isolated sets.
 UF(int N)  {
 cnt = N;
 id = new int[N];
 sz = new int[N];
 for (int i = 0; i<N; i++) {
  id[i] = i;
  sz[i] = 1;
 }
 }
 ~UF() {
 delete[] id;
 delete[] sz;
 }
 // Return the id of component corresponding to object p.
 int find(int p) {
 
 if (p != id[p]){
  id[p] = find(id[p]);
 }
 return id[p];
 }
 // Replace sets containing x and y with their union.
 void merge(int x, int y) {
 int i = find(x);
 int j = find(y);
 if (i == j) return;

 // make smaller root point to larger one
 if (sz[i] < sz[j]) {
  id[i] = j;
  sz[j] += sz[i];
 }
 else {
  id[j] = i;
  sz[i] += sz[j];
 }
 cnt--;
 }
 // Are objects x and y in the same set&#63;
 bool connected(int x, int y)  {
 return find(x) == find(y);
 }
 // Return the number of disjoint sets.
 int count() {
 return cnt;
 }
};

void main(){
 UF test(5);
 test.merge(2, 3);
 test.merge(3, 4);
 cout << test.find(4);
 cout << test.count();
}

看完了這篇文章,相信你對C++是如何實現(xiàn)并查集的有了一定的了解,想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI