1. (15%) [圖:13 個節點的無向圖。節點 7 的鄰居是 2、3、4、5、6,節點 10 的鄰居是 2、3。]
We define common friends between node A and node B are the common neighbors of node A and node B. For example, in the above graph the common friends between node 7 and node 10 are node 2 and node 3. Assuming the neighbor list of each node is given, please write a function NumCommonFriend(node A, node B) to return the number of common friends between node A and B in the given graph. Note that you should optimize your code by reducing the number of operations.
兩個 neighbor list 求交集的大小。令 \(d_A,d_B\) 是兩點的 degree
做法 1(list 已排序):兩個指標同時走,像 merge:\(O(d_A+d_B)\)
做法 2(最省):走 degree 較小的那個 list,對每個鄰居查「它是不是另一個點的鄰居」。另一個點的鄰居事先放進 hash set(或 bit vector,每個點一個 \(O(1)\) 查詢):\(O(\min(d_A,d_B))\)
int NumCommonFriend(node A, node B)
{
if (deg[A] > deg[B]) swap(A, B); /* A 的 neighbor 較少 */
int cnt = 0;
for (each v in neighbor[A]) /* 只走較短的 list */
if (isNeighbor(B, v)) /* O(1):hash set 或 bit vector */
cnt++;
return cnt;
}
若沒有事先建好 hash set,也可以拿較長的 list 建 hash(\(O(d_B)\))再走較短的;或 list 已排序時,對較短 list 的每個元素在長 list 做 binary search:\(O(d_A\lg d_B)\),\(d_A\ll d_B\) 時比 merge 少
題目的例子:node 7 的鄰居 \(\{2,3,4,5,6\}\)、node 10 的鄰居 \(\{2,3\}\);走 10 的 list,2、3 都是 7 的鄰居 → 回傳 2
走較小的 neighbor list,每個元素在另一邊的 hash set 查詢,\(O(\min(d_A,d_B))\)