假如已知有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属于另一个朋友圈,结果为两个朋友圈。
这道题有很多种解法,首先想到的就是定义一个数组,数组元素也是数组。使用STL库,定义这样的一个结构:
vector<vector<int>> _v;
然后遍历每对好友关系,如果数组中有相同元素(好友),就在当前数组中添加该好友,最后,遍历最外层数组元素个数就可以知道有多少个朋友圈了。
作为小米面试题,它不仅要求正确性还有效率,上面给出的解法也能做出这道题,但是效率太低,所以,在这里,我使用一种更高效,快捷的数据结构-----并查集。
并查集:
并查集是一种树型的数据结构,用于处理一些不相交集合(Disjoint Sets)的合并及查询问题。常常在使用中以森林来表示。集就是让每个元素构成一个单元素的集合,也就是按一定顺序将属于同一组的元素所在的集合合并。在一些有N个元素的集合应用问题中,通常是在开始时让每个元素构成一个单元素的集合,然后按一定顺序将属于同一组的元素所在的集合合并,其间要反复查找一个元素在哪个集合中。
如图所示:
查找根:
int GetRoot(int root)
{
if(_unionset[root] >= 0) //_unionset[]为负数时找到
{
root = _unionset[root];
}
return root;
}
合并朋友圈(判断x1与x2是否已经为好友关系,不是则并合并到所在朋友圈):
void Union(int x1,int x2)
{
int root1 = GetRoot(x1);
int root2 = GetRoot(x2);
if(root1 != root2)
{
_unionset[root1] += _unionset[root2];
_unionset[root2] = root1;
}
}
计算朋友圈个数:
int Count()
{
int count = 0;
for(int i = 0; i<_n; ++i)
{
if(_unionset[i] < 0)
count++;
}
return count-1;//因为0号位置不用,但初始化时初始化为了-1,需要减去多算的这一个
}
整体代码:
#pragma once
#include <iostream>
using namespace std;
#include <vector>
#include <cassert>
class UnionSet
{
public:
UnionSet(int n)
:_n(n)
{
_unionset = new int[n];
//memset(_unionset,-1,sizeof(int)*n);memset按字节处理,只能初始化为0,1,-1
//安全起见,都用for循环处理
for(int i = 0; i<n; ++i)
{
_unionset[i] = -1;
}
}
int GetRoot(int root)
{
if(_unionset[root] >= 0)
{
root = _unionset[root];
}
return root;
}
void Union(int x1,int x2)
{
int root1 = GetRoot(x1);
int root2 = GetRoot(x2);
if(root1 != root2)
{
_unionset[root1] += _unionset[root2];
_unionset[root2] = root1;
}
}
bool Find(int x1,int x2)
{
int root1 = GetRoot(x1);
int root2 = GetRoot(x2);
return root1 == root2;
}
int Count()
{
int count = 0;
for(int i = 0; i<_n; ++i)
{
if(_unionset[i] < 0)
count++;
}
return count-1;
}
protected:
//vector<int> v;
int* _unionset;
int _n;
};
int Friend(int n,int m,int r[][2])
{
assert(r);
UnionSet u(n+1);//多开一个空间,0号位置不用
for(int i = 0;i<m;++i)
{
int r1 = r[i][0];
int r2 = r[i][1];
u.Union(r1,r2);
}
return u.Count();
}
Test.cpp
void Test1()
{
int r[4][2] = {{1,2},{2,3},{4,5},{1,3}};//n=总人数,m=多少对好友关系
cout<<"朋友圈?"<<Friend(5,4,r)<<endl;
}
void Test2()
{
int r[][2] = {{1,2},{2,3},{4,5},{5,9},{6,2},{7,8}};//n=总人数,m=多少对好友关系
cout<<"朋友圈?"<<Friend(9,6,r)<<endl;
}