C++利用map實現(xiàn)并查集
并查集(Union-Find)是一種樹型的數(shù)據(jù)結構,用于處理一些不相交集合(Disjoint Sets)的合并及查詢問題。 并查集存在兩個操作(1.Union 聯(lián)合 2.finddeputy 查找代表結點) 和一個需要解答的問題( issameset 是否 在一個集合中,或者說是否有同一個代表結點)。
利用map實現(xiàn)主要通過兩個map的對象 ,一個map<data,data>類型的fathermap,關鍵字為子結點,值為其父結點(父結點不一定就是代表結點),當我們需要查找兩個兩個元素是否在一個集合中時,只需一直向上找(函數(shù)finddupty),在找的過程中,會壓縮路徑,把沿途經過的結點直接掛在其代表結點下,看是否有共同的代表結點;
一個map<data,int>類型的sizemap,key為結點,value為其子結點的個數(shù)(這個個數(shù)只對代表結點有效,子結點無效),主要用處是在合并(union)時將子結點較少的代表結點掛在子結點代表較多的代表結點下,且sizemap中父結點對應的value要加上子結點較少的代表的結點個數(shù)。
代碼如下:
#include<map>
#include<list>
#include<iostream>
using namespace std;
template<typename data>
class Unionfindset{
public:
void makesets(list<data> nodes)
{
fathermap.clear();
sizemap.clear();
for(auto node:nodes)
{
fathermap[node]=node;
sizemap[node]=1;
}
}
//尋找代表結點,且路徑壓縮
data findduputy(data node)
{
data father=fathermap[node];
if(father!=node)
{
return findduputy(father);
}
fathermap[node]=father;
return father;
}
void Union(data a ,data b)
{
data ahead=findduputy(a);
data bhead=findduputy(b);
if(ahead!=bhead)
{
data asize=sizemap[a];
data bsize=sizemap[b];
if(asize<bsize)
{
fathermap[a]=b;
sizemap[b]=bsize+asize;
}
else
{
fathermap[b]=a;
sizemap[a]=bsize+asize;
}
}
}
bool issameset(data a,data b)
{
return findduputy(a)==findduputy(b);
}
private:
map<data,data> fathermap;
map<data,data> sizemap;
};
謝謝閱讀,歡迎指出錯誤!
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Pipes實現(xiàn)LeetCode(194.轉置文件)
這篇文章主要介紹了Pipes實現(xiàn)LeetCode(194.轉置文件),本篇文章通過簡要的案例,講解了該項技術的了解與使用,以下就是詳細內容,需要的朋友可以參考下2021-08-08

