【面試題】例如已知有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屬於另一個朋友圈。結果爲2個朋友圈。
最後請分析所寫代碼的時間、空間複雜度。評分會參考代碼的正確性和效率。
c/c++:
int friends(int n, int m, int * r[])
java:
int friends(int n, int m, int [][] r)
分析:可能大家會想到用數組統計存在好友關係的人名,但此方法對於好友關係複雜,人數較多時,效率較低。我們可以通過並查集思進行實現。
並查集:
(1)將N個不同的元素分成一組不相交的集合。
(2)開始時,每個元素就是一個集合,然後按規律將兩個集合進行合併。
例如下圖:
具體實現如下:
#pragma once
class UnionSet
{
public:
UnionSet()
:_set(NULL)
, _n(0)
{}
UnionSet(size_t size)
:_set(new int(size))
, _n(size)
{
size_t i = 0;
for (; i < size; ++i)//初始化數組爲-1
{
_set[i] = -1;
}
_set[i] = '\0';
}
void Union(int root1, int root2)//root1和root2是好友,以一個人爲這個朋友圈的核心,找到與其相關的朋友
{
assert(_set[root1] < 0);
assert(_set[root2] < 0);
_set[root1] += _set[root2];
_set[root2] = root1;
}
size_t FindRoot(int root)//找到root所屬的這個朋友圈的核心,
{
while (_set[root] >= 0)//說明不是朋友圈的根結點
{
root = _set[root];//向朋友圈的上一級找,直到爲負數結束
}
return root;
}
void Count()
{
int count = 0;
for (size_t i = 0; i < _n; ++i)
{
if (_set[i] < 0)
count++;
}
cout << count << endl;
}
private:
int* _set;
size_t _n;
};
size_t Find(int* a, int root)
{
assert(a);
while (a[root] >= 0)
root = a[root];
return root;
}
int FindFriends(int n, int m, int r[][2])//n個人,m對好友關係,r[][2]二維數組表示關係的兩個人
{
int* a = new int[n];
for (size_t i = 0; i < n; ++i)//初始化數組
{
a[i] = -1;
}
int root1 = 0, root2 = 0;
for (size_t i = 0; i < m; ++i)
{
root1 = Find(a, r[i][0]);//找根
root2 = Find(a, r[i][1]);
if (root1 != root2)
{
a[root1] += a[root2];
a[root2] = root1;
}
}
int count = 0;
for (size_t i = 0; i < n; ++i)
{
if (a[i] <= 0)
count++;
}
return count;
}
void UnionSetTest()
{
UnionSet us(10);
us.Union(0, 6);
us.Union(0, 7);
us.Union(0, 8);
us.Union(1, 4);
us.Union(1, 9);
us.Union(2, 3);
us.Union(2, 5);
cout << us.FindRoot(9) << endl;
us.Count();//朋友圈的個數
int r[8][2] = { { 1, 4 }, { 1, 9 }, { 2, 3 }, { 2, 5 }, { 0, 6 }, { 0, 7 }, { 0, 8 }, { 8, 9 } };
cout << FindFriends(10, 7, &r[0]) << endl;
}
不用類進行實現,如下所示
#include<assert.h>
size_t Find(int* a, int root)
{
assert(a);
while (a[root] >= 0)
root = a[root];
return root;
}
int FindFriends(int n, int m, int r[][2])//n個人,m對好友關係,r[][2]二維數組表示關係的兩個人
{
int* a = new int[n];
for (size_t i = 0; i < n; ++i)//初始化數組
{
a[i] = -1;
}
int root1 = 0, root2 = 0;
for (size_t i = 0; i < m; ++i)
{
root1 = Find(a, r[i][0]);//注意找根
root2 = Find(a, r[i][1]);
if (root1 != root2)
{
a[root1] += a[root2];
a[root2] = root1;
}
}
int count = 0;
for (size_t i = 0; i < n; ++i)
{
if (a[i] < 0)
count++;
}
return count;
}
void FriendsTest()
{
int r[8][2] = { { 1, 4 }, { 1, 9 }, { 2, 3 }, { 2, 5 }, { 0, 6 }, { 0, 7 }, { 0, 8 }, { 8, 9 } };
cout << FindFriends(10, 8, &r[0]) << endl;
}