朋友圈(使用並查集)的實現

#pragma once

#include<iostream>

using namespace std;

class UnionFindSet

{

public:

UnionFindSet(int n)

{

_n = n + 1;

_set = new int[_n];

for (int i = 1; i < _n; ++i)

{

_set[i] = -1;

}

}

int GetFriendSet(int n, int m, int r[][2])

{

for (int i = 0; i < m; ++i)

{

UnionfriendSet(r[i][0],r[i][1] );

}

int count = 0;

for (int i = 1; i < _n; ++i)

{

if (_set[i] <0)

++count;

}

return count;

}

void UnionfriendSet(int n,int m)

{

int root1 = GetRoot(n);

int root2 = GetRoot(m);

if (root1 != root2)

{

_set[root1] += _set[root2];

_set[root2] = root1;

}

}

int GetRoot(int x)

{

while (_set[x] >= 0)

{

x = _set[x];

}

return x;

}

protected:

int *_set;

size_t _n;

};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章