十年網(wǎng)站開(kāi)發(fā)經(jīng)驗(yàn) + 多家企業(yè)客戶(hù) + 靠譜的建站團(tuán)隊(duì)
量身定制 + 運(yùn)營(yíng)維護(hù)+專(zhuān)業(yè)推廣+無(wú)憂售后,網(wǎng)站問(wèn)題一站解決
定義
并查集是一種樹(shù)型的數(shù)據(jù)結(jié)構(gòu),用于處理一些不相交集合(Disjoint Sets)的合并及查詢(xún)問(wèn)題。常常在使用中以森林來(lái)表示。
應(yīng)用
若某個(gè)朋友圈過(guò)于龐大,要判斷兩個(gè)人是否是在一個(gè)朋友圈,確實(shí)還很不容易,給出某個(gè)朋友關(guān)系圖,求任意給出的兩個(gè)人是否在一個(gè)朋友圈。 規(guī)定:x和y是朋友,y和z是朋友,那么x和z在一個(gè)朋友圈。如果x,y是朋友,那么x的朋友都與y的在一個(gè)朋友圈,y的朋友也都與x在一個(gè)朋友圈。
如下圖:
代碼:
//找朋友圈個(gè)數(shù) //找父親節(jié)點(diǎn) int FindRoot(int child1, int *_set) { int root = child1; while (_set[root] >= 0) { root = _set[root]; } return root; } //合并 void Union(int root1, int root2, int *&_set) { _set[root1] += _set[root2]; _set[root2] = root1; } int Friend(int n, int m, int r[][2])//n為人數(shù),m為組數(shù),r為關(guān)系 { assert(n > 0); assert(m > 0); assert(r); int *_set = new int[n]; for (int i = 0; i < n+1; i++) { _set[i] = -1; } for (int i = 0; i < m; i++) { int root1 = FindRoot(r[i][0],_set); int root2 = FindRoot(r[i][1],_set); if ((_set[root1] == -1 && _set[root2] == -1) || root1 != root2) { Union(root1, root2, _set); } } int count = 0; for (int i = 1; i <= n; i++) { if (_set[i] < 0) { count++; } } return count; } //主函數(shù) #define _CRT_SECURE_NO_WARNINGS 1 #includeusing namespace std; #include #include"UnionFindSet.h" int main() { int r[][2] = { { 1, 2 }, { 2, 3 }, { 3, 4 }, { 5, 6 } }; cout << Friend(6, 4, r) << endl; system("pause"); return 0; }
另外有需要云服務(wù)器可以了解下創(chuàng)新互聯(lián)scvps.cn,海內(nèi)外云服務(wù)器15元起步,三天無(wú)理由+7*72小時(shí)售后在線,公司持有idc許可證,提供“云服務(wù)器、裸金屬服務(wù)器、高防服務(wù)器、香港服務(wù)器、美國(guó)服務(wù)器、虛擬主機(jī)、免備案服務(wù)器”等云主機(jī)租用服務(wù)以及企業(yè)上云的綜合解決方案,具有“安全穩(wěn)定、簡(jiǎn)單易用、服務(wù)可用性高、性?xún)r(jià)比高”等特點(diǎn)與優(yōu)勢(shì),專(zhuān)為企業(yè)上云打造定制,能夠滿(mǎn)足用戶(hù)豐富、多元化的應(yīng)用場(chǎng)景需求。