朋友圈问题(并查集)

问题描述:

        假如已知有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 
using namespace std;

class UnionSet
{
public:
	UnionSet(int n)
		:a(new int[n])
	{
		/*int* a=new int[n];*/
		for(int i=0;i= 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


你可能感兴趣的:(算法与数据结构,数据结构)