求朋友圈的个数---并查集

问题:
1、已知,有n个人和m对好友关系(存于一个集合r中)
2、如果两个人是直接的或者间接的好友,(那么他们的朋友圈可以合并)

则以下为例:

int a[][2] = { { 1, 2 }, { 2, 3 }, { 4, 5 } };

1)有5个人开辟6个整型数组,并初始化为-1

求朋友圈的个数---并查集_第1张图片

2)合并同一个朋友圈的人

{1,2}的领导人是1,{2,3}的领导人是2,要将同一个朋友圈的人都合并到领导人下

求朋友圈的个数---并查集_第2张图片

3.遍历数组,则遍历到的负数的个数就是朋友圈的个数,但要除去0号位置的-1。

代码如下;

#include

class UnionSet
{
public:
	UnionSet(size_t N)
	{
		//有5个人开辟6个整型数组,并初始化为-1
		_sets.resize(N+1,-1);
	}
	int FindRoot(int x)
	{
		while (_sets[x] >= 0)//找到对应朋友
		{
			x -= _sets[x];
		}
		return x;
	}
	//合并同一个朋友圈的人
	void UnionFriends(int x1,int x2)	
	{
		int root1 = FindRoot(x1);
		int root2 = FindRoot(x2);
		if (root1 != root2)
		{
			_sets[root1] += _sets[root2];
			_sets[root2] = root1;
		}
	}
	int Friends(int n, int m, int r[][2])
	{
		int counts = 0;
		for (int i = 0; i < m; i++)
		{
			UnionFriends(r[i][0],r[i][1]);
		}
		//计算朋友圈的个数
		for (int i = 1; i < n + 1; i++)//注意我是从1开始遍历,如果从0开始,就要减掉1
		{
			if (_sets[i] < 0)
				counts++;
		}
		return counts;
	}
protected:
	vector _sets;
};
void test()
{
	int a[][2] = { { 1, 2 }, { 2, 3 }, { 4, 5 } };
	int n = 5, m = 3;
	UnionSet u(n);
	cout<
哈哈完了!!!



你可能感兴趣的:(cpp)