您的位置:首页 > 理论基础 > 数据结构算法

朋友圈(使用并查集)的实现

2016-07-09 23:25 260 查看
#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;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息