#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;
};
时间: 2024-11-08 08:40:35