溫馨提示×

溫馨提示×

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

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

C++ set在并查集優(yōu)化中的應(yīng)用

發(fā)布時(shí)間:2024-08-05 15:52:09 來源:億速云 閱讀:79 作者:小樊 欄目:編程語言

在并查集(Disjoint Set Union)的優(yōu)化中,可以使用C++的set容器來實(shí)現(xiàn)路徑壓縮和按秩合并。路徑壓縮是指在查找根節(jié)點(diǎn)的過程中,將沿途的節(jié)點(diǎn)的父節(jié)點(diǎn)直接設(shè)為根節(jié)點(diǎn),以減少查找路徑的長度。按秩合并是指將兩個(gè)集合合并時(shí),將rank較小的樹作為rank較大的樹的子樹,以減少樹的深度。

下面是一個(gè)使用C++的set容器實(shí)現(xiàn)并查集優(yōu)化的示例代碼:

#include <iostream>
#include <set>
#include <vector>

using namespace std;

class UnionFind {
public:
    vector<int> parent;
    vector<int> rank;

    UnionFind(int n) {
        parent.resize(n);
        rank.resize(n, 0);
        for (int i = 0; i < n; i++) {
            parent[i] = i;
        }
    }

    int find(int x) {
        if (parent[x] != x) {
            parent[x] = find(parent[x]);
        }
        return parent[x];
    }

    void unite(int x, int y) {
        int rootX = find(x);
        int rootY = find(y);

        if (rootX != rootY) {
            if (rank[rootX] < rank[rootY]) {
                parent[rootX] = rootY;
            } else if (rank[rootX] > rank[rootY]) {
                parent[rootY] = rootX;
            } else {
                parent[rootY] = rootX;
                rank[rootX]++;
            }
        }
    }
};

int main() {
    UnionFind uf(5);

    uf.unite(0, 1);
    uf.unite(1, 2);
    uf.unite(3, 4);

    cout << uf.find(0) << endl; // output: 1
    cout << uf.find(2) << endl; // output: 1
    cout << uf.find(3) << endl; // output: 4

    return 0;
}

在上面的示例代碼中,我們使用了C++的set容器來存儲(chǔ)父節(jié)點(diǎn),并實(shí)現(xiàn)了路徑壓縮和按秩合并。通過這種方式,可以優(yōu)化并查集的性能,使其在實(shí)際應(yīng)用中更加高效。

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

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

c++
AI