并查集套用碼

class Djset {

private:

? ? vector<int> parent;? // 記錄節(jié)點的根

? ? vector<int> rank;? // 記錄根節(jié)點的深度(用于優(yōu)化)

? ? int count;? ? ? ? // 記錄連通分量的個數(shù)

? ? int rest;? ? ? ? ? // 記錄多余的連接數(shù)

public:

? ? Djset(int n): parent(vector<int>(n)), rank(vector<int>(n)), count(n), rest(0) {

? ? ? ? for (int i = 0; i < n; i++) {

? ? ? ? ? ? parent[i] = i;

? ? ? ? }

? ? }

? ?

? ? int find(int x) {

? ? ? ? // 壓縮方式:直接指向根節(jié)點

? ? ? ? if (x != parent[x]) {

? ? ? ? ? ? parent[x] = find(parent[x]);

? ? ? ? }

? ? ? ? return parent[x];

? ? }

? ?

? ? void merge(int x, int y) {

? ? ? ? int rootx = find(x);

? ? ? ? int rooty = find(y);

? ? ? ? if (rootx != rooty) {

? ? ? ? ? ? // 按秩合并

? ? ? ? ? ? if (rank[rootx] < rank[rooty]) {

? ? ? ? ? ? ? ? swap(rootx, rooty);

? ? ? ? ? ? }

? ? ? ? ? ? parent[rooty] = rootx;

? ? ? ? ? ? if (rank[rootx] == rank[rooty]) rank[rootx] += 1;

? ? ? ? ? ? count--;

? ? ? ? } else {

? ? ? ? ? ? rest++;

? ? ? ? }

? ? }

? ? int getCount() {

? ? ? ? return count;

? ? }

? ? int getRest() {

? ? ? ? return rest;

? ? }

};

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容