朋友圈问题(并查集)

问题描述:

        假如已知有n个人和m对好友关系(存于数字r)。如果两个人是直接或间接的好友(好友的好友的好友...),则认为他们属于同一个朋友圈,请写出程序求出这n个人里一共有多少朋友圈。

        例如:n=5,m=3,r={{1,2},{2,3},{4,5}},表示有5个人,1和2是好友,2和3是好友,4和5是好友。则1,2,3属于一个朋友圈,4,5属于另一个朋友圈,结果为两个朋友圈。

根据问题:我们可以用数据结构里的并查集来解决此问题。

问题解决:

#include <iostream>
using namespace std;

class UnionSet
{
public:
	UnionSet(int n)
		:a(new int[n])
	{
		/*int* a=new int[n];*/
		for(int i=0;i<n;i++)
		{
			a[i]=-1;
		}
	}

	~UnionSet()
	{
		if(a != NULL)
			delete a;
	}

	int FindRoot(int x)
	{
		int root=x;
		while(a[root] >= 0)
		{
			root--;
		/*	root=a[root];*/
		}
		return root;
	}

	void Union(int root1,int root2)
	{
		int _root1=FindRoot(root1);
		int _root2=FindRoot(root2);
		if(root1 != root2)
		{
			a[_root1]+=a[_root2];
		    a[_root2]=_root1;
		}
	}

	int count(int n)
	{
		int count=0;
		for(int i=0;i<n;i++)
		{
			if(a[i] < 0)
				count++;
		}
		return count-1;
	}
private:
	int *a;
};

int Friends(int n,int m,int r[][2])  //int *r[]  
{
	UnionSet u(n+1);
	for(int i=0;i<m;i++)
	{
		u.Union(r[i][0],r[i][1]);
	}
	return u.count(n+1);
}


  • 8
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值