您的位置:首页 > 其它

朋友圈问题(并查集)

2017-04-01 19:50 176 查看
问题描述:

        假如已知有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
)
{
/*int* a=new int
;*/
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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: