免費詳解 / 師大 / 軟體 / 104

104 師大資工所考古題解答|軟體逐題詳解

104 師大資工所軟體考古題的逐題詳解,共 8 題,免費公開。

逐題詳解

110 分

Given several documents where the title of each document consists of a sequence of words as follows:

d1: “Set up your Apple ID for iCloud and iTunes” d2: “If your Apple ID has been locked” d3: “Apple Watch: Release date, price and specs” d4: “How to view iCloud Drive files on iPhone and iPad”

You would like to write a program to support the full text retrieval function: i.e. by giving one or more words as a query, your program has to return the IDs of the documents whose titles contain all the words in the query. For example, if the query is “Apple”, the program should output documents d1, d2, and d3. If the query is “iCloud” and “iPad”, the program should output document d4.

(a) (5 分) Please design a data structure to be the index structure such that the full text retrieval function can be performed efficiently. Please also show the constructed index structure for the given 4 documents.

(b) (5 分) Please show the pseudo codes and explain how to perform the full text retrieval function according to the designed data structure efficiently.

(a) inverted index:以 word 為 key,值是出現過這個 word 的 document ID 清單(posting list),清單依 ID 由小到大排好。key 放在 hash table(或 trie、balanced BST),用 word 一步查到它的 posting list

建法:逐篇文件把標題切成字(轉小寫),每個字把這篇文件的 ID 加到該字的 posting list 尾端(文件由小到大處理,所以清單自然排好)

wordposting listwordposting listwordposting list
appled1, d2, d3icloudd1, d4andd1, d3, d4
yourd1, d2idd1, d2set, up, for, itunesd1
if, has, been, lockedd2watch, release, date, price, specsd3how, to, view, drive, files, on, iphone, ipadd4

(b) 查詢(字 \(w_1,\dots,w_k\)):

search(w1..wk):
  for i = 1..k:
      L[i] = index.lookup(lower(wi))        // hash 查詢,期望 O(1)
      if L[i] is empty: return {}           // 有一個字沒出現過,答案是空的
  sort L by length ascending                // 由最短的 list 開始
  result = L[1]
  for i = 2..k:
      result = intersect(result, L[i])      // 兩個有序 list 的交集
      if result is empty: return {}
  return result

intersect(A, B):                             // A、B 已排序
  p = 0; q = 0; R = []
  while p < |A| and q < |B|:
      if A[p] == B[q]: R.append(A[p]); p++; q++
      else if A[p] < B[q]: p++
      else: q++
  return R

時間:查字 \(O(k)\);交集每次 \(O(|A|+|B|)\),總共 \(O\bigl(\sum_i|L_i|\bigr)\),與全部文件總字數無關(不必每次掃所有標題)

例:query iCloud、iPad:\(\{d1,d4\}\cap\{d4\}=\{d4\}\) ✓;query Apple:\(\{d1,d2,d3\}\) ✓。先從最短的 list 開始,結果最小,後面比對更少

215 分

Suppose you would like to construct a data structure for a dictionary of the following words to store the words and their page numbers: “able” (p12), “cat”(p10), “cook”(p1), “book”(p5), “look”(p8), “apple”(p3), “eat”(p12), “fruit”(p30), “it”(p23), “bike”(p15). Then your goal is to write a program to find the page number of a given word. If the given word is not in the dictionary, return “not found”.

(a) (6 分) Please show how to store the words in an array such that you can perform the binary search algorithm to find the page number of a given word. Please also show the pseudo codes of the binary search algorithm.

(b) (4 分) Please describe the advantage and disadvantage of using a linked-list to maintain the words and their page numbers compared with using an array.

(c) (5 分) Please design a data structure for the words such that all the words beginning with a given prefix can be found efficiently. For example, when you give a prefix “a”, the system will find “able” and “apple”. When you give “ab”, the system will find “able”.

(a) 陣列元素放 (word, page),依 word 字典序排好:

index0123456789
wordableapplebikebookcatcookeatfruititlook
page1231551011230238
binarySearch(D[0..n-1], key):
  lo = 0; hi = n - 1
  while lo <= hi:
      mid = (lo + hi) / 2
      c = compare(key, D[mid].word)        // 字典序比較
      if c == 0: return D[mid].page
      else if c < 0: hi = mid - 1
      else: lo = mid + 1
  return "not found"

每次比較把範圍減半,\(O(\log n)\)

例:查 “cook”:mid=4(cat)→ cook 較大,lo=5;mid=7(fruit)→ 較小,hi=6;mid=5(cook)找到,page 1

(b) linked list 的優點:

新增、刪除不用搬動其他元素(找到位置後 \(O(1)\)),陣列要把後面整段往後移 \(O(n)\);大小可動態增減,不需事先決定或擴充;不必要連續記憶體

缺點:

不能 random access,沒辦法做 binary search,查找只能從頭走,\(O(n)\)(即使排好序也一樣);每個節點多存 pointer,浪費空間;節點散在記憶體各處,cache 效能差

(c) 用 trie(prefix tree):每個節點代表一個字母,從 root 到某節點的路徑就是一個前綴;單字結尾的節點記錄 page 號碼

ep12lbep3lppaep15kikp5oobtp10akp1ooctp12aetp30iurftp23ikp8oolroot

查前綴 \(p\):從 root 照 \(p\) 的每個字母往下走(\(|p|\) 步,走不下去就是沒有這個前綴的字),到達前綴對應的節點後,把它整棵子樹走一遍,收集所有標記為詞尾的節點

例:前綴 “a”:走到 a,子樹有 able、apple;前綴 “ab”:走到 ab,子樹只有 able

時間 \(O(|p|+\text{輸出大小})\),與字典總大小無關。另一種做法:排序陣列,用 binary search 找到第一個 ≥ 前綴的位置,往後掃到不再以該前綴開頭為止,\(O(\log n+m)\)

310 分

Continued from the previous question.

(a) (4 分) Please describe how to store the above words in a hash table with 5 buckets, where each bucket has 2 slots.

(b) (6 分) Please explain the problems of “collision” and “overflow” when constructing a hash table. How to handle these problems?

(a) hash function:\(h(w)=\bigl(\text{字母序號之和}\bigr)\bmod5\)(a=1,b=2,…);依題目順序插入,同一個 bucket 先到的放第一格

wordablecatcookbooklookappleeatfruititbike
字母和20244443535026742927
\(h(w)\)0443301442

fruit 與 it 的 bucket 4 已被 cat、cook 占滿(overflow),往下一個 bucket(4 → 0 → 1 → 2…)找有空位的:fruit 0 已滿,放進 1;it 0、1 都滿,放進 2;bike 的 bucket 2 還有一格

bucketslot 1slot 2
0able(p12)apple(p3)
1eat(p12)fruit(p30)
2it(p23)bike(p15)
3book(p5)look(p8)
4cat(p10)cook(p1)

查找:算 \(h(w)\),在該 bucket 的兩格找;找不到而 bucket 已滿,就繼續看下一個 bucket,直到找到、遇到有空位的 bucket(表示不在)、或繞一圈回來

(b) collision:兩個不同的 key 算出相同的 hash 值(同一個 bucket)。這裡 able 與 apple 都是 bucket 0。bucket 有多個 slot 時,collision 還能放進空的 slot

overflow:新的 key 的 home bucket 已經沒有空 slot(所有 slot 都被占)。這裡 cat、cook 占滿 bucket 4,後來的 fruit、it 就 overflow

處理方法:

① 好的 hash function,讓 key 分布均勻,減少 collision

② open addressing(linear probing、quadratic probing、double hashing):到別的 bucket 找空位,查找時依同樣的 probe 順序

③ chaining/overflow chain:每個 bucket 後面接 linked list,放不下的接在後面

④ 增加 bucket 數或 slot 數,必要時 rehash 到更大的 table(load factor 太高就擴大)

⑤ 另設 overflow area,放 overflow 的資料

415 分

Suppose that there are 6 users on a social networking site as follows. John, Mary, Tony, Andy, Paul, and Kelly. The friendships between the users are as follows: (John, Mary), (John, Tony), (Paul, Kelly), (Tony, Paul), and (Mary, Andy). Note that the friendships are bi-directional. For example, according to the given friendship (John, Mary), John is a friend of Mary and Mary is a friend of John.

(a) (3 分) Please design a data structure to maintain the friendships of the 6 users.

(b) (4 分) Suppose there are N users in the social networking site. What is the time complexity to find the users who do not have any friend in the site? (i) If you use an adjacency matrix; (ii) if you use an adjacency list. Please explain your answer.

(c) (5 分) Suppose a function DFS(v) is provided which can traversal the friendship graph in depth first search starting at node v and mark each visited node as “visited”. Please give the pseudo codes to count the number of connected components in the friendship graph.

(d) (3 分) In the DFS(v) function, please explain how to detect that the edges of the visited nodes starting at node v form a cycle?

(a) 無向圖,用 adjacency list:每個使用者對應一條 list,存他所有朋友(朋友關係是雙向的,一條友誼在兩端的 list 各存一次)

userfriends
JohnMary → Tony
MaryJohn → Andy
TonyJohn → Paul
AndyMary
PaulKelly → Tony
KellyPaul

用 6×6 的 adjacency matrix 也可以(對稱矩陣,\(M[i][j]=1\) 表示 \(i,j\) 是朋友);使用者多、朋友少的社群網站,list 省空間(\(O(N+E)\) 對 \(O(N^2)\))

(b) (i) adjacency matrix:要確認一列全部是 0,每個使用者要看 \(N\) 格,共 \(N\) 個使用者

(i) \(O(N^2)\)

(ii) adjacency list:沒有朋友的使用者,他的 list 是空的;只要檢查每個使用者的 list 是不是空(看 head 指標),每人 \(O(1)\)

(ii) \(O(N)\)

(c) 每個 DFS 會走完一個 connected component,從還沒走過的點開始再跑一次 DFS 就是新的 component

countComponents(G):
  for each user v: visited[v] = false
  count = 0
  for each user v:
      if visited[v] == false:
          DFS(v)              // 把 v 所在 component 全標成 visited
          count++
  return count

這張圖:Andy-Mary-John-Tony-Paul-Kelly 連成一條線,從 John 開始 DFS 就走完 6 個人,count=1

(d) 在無向圖的 DFS 中,記錄每個點的 parent(是從哪個點走過來的)。走到點 \(u\) 檢查鄰居 \(w\):

\(w\) 還沒 visited:遞迴 DFS(\(w\)),parent[\(w\)] = \(u\)

\(w\) 已經 visited,而且 \(w\) 不是 \(u\) 的 parent:找到一條 back edge \((u,w)\),它與 DFS tree 上 \(w\) 到 \(u\) 的路徑構成 cycle

不能把「走回 parent」算成 cycle,因為無向邊 \((u,\text{parent})\) 本來就會從兩端各看到一次;若有重複的邊(同兩人有兩條友誼)則另外視為 cycle。等價判準:一個 component 的邊數 ≥ 點數就有 cycle(tree 的邊數 = 點數 − 1)

515 分

Consider the following algorithm expressed in pseudocode:

void Comp (int n, const number A[][], const number B[][], number C[][])
{
   index i, j, k;
   for (i=1; j<=n; j++)
      for (j=1; j<=n; j++){
         C[i][j] = 0;
         for (k=1; k<=n; k++)
            C[i][j] = C[i][j] + A[i][k] * B[k][j];
      }
}

(a) (3 分) What does this algorithm compute? (b) (3 分) If n=2, \(A=\begin{bmatrix}3&1\\2&5\end{bmatrix}\), and \(B=\begin{bmatrix}4&7\\8&6\end{bmatrix}\), what is the value of C after running this algorithm? (c) (3 分) What is the time complexity T(n) of this algorithm in terms of big-O notation? (d) (3 分) Is the above algorithm a “polynomial-time algorithm”? Why? (e) (3 分) In 1969, Strassen published an algorithm whose time complexity is better than the above algorithm. Strassen algorithm is categorized as “divide-and-conquer algorithm”. Why?

(a) \(C[i][j]=\sum_{k=1}^{n}A[i][k]\,B[k][j]\):兩個 \(n\times n\) 矩陣相乘 \(C=A\times B\)

第一層迴圈印成 for (i=1; j<=n; j++),應是 i<=n; i++ 的筆誤;照字面 \(i\) 一直是 1,外層只跑一次,只算出 \(C\) 的第一列。以下依原意作答

(b) \(C=\begin{bmatrix}3&1\\2&5\end{bmatrix}\begin{bmatrix}4&7\\8&6\end{bmatrix}\)

\(C_{11}=3\cdot4+1\cdot8=20\);\(C_{12}=3\cdot7+1\cdot6=27\)

\(C_{21}=2\cdot4+5\cdot8=48\);\(C_{22}=2\cdot7+5\cdot6=44\)

\(C=\begin{bmatrix}20&27\\48&44\end{bmatrix}\)

(c) \(i,j,k\) 三層迴圈各跑 \(n\) 次,內層一次乘法加一次加法

\(T(n)=n^3\) 次乘法 → \(O(n^3)\)

(d) 是。執行時間 \(O(n^3)\) 被輸入大小的多項式限制住(輸入有 \(2n^2\) 個數字,\(n^3\le(2n^2)^{3/2}\))

是 polynomial-time algorithm

(e) Strassen 把問題切成同型的較小子問題,分別解出,再合併:

① divide:把 \(n\times n\) 矩陣切成四個 \(\tfrac n2\times\tfrac n2\) 的子矩陣

② conquer:用 7 次(不是一般的 8 次)\(\tfrac n2\) 階矩陣乘法(遞迴呼叫自己)算出 7 個乘積 \(M_1,\dots,M_7\)

③ combine:用 \(O(n^2)\) 的矩陣加減法把 \(M_1\dots M_7\) 組成 \(C\) 的四個子區塊

\(T(n)=7T(n/2)+\Theta(n^2)\) → \(T(n)=\Theta(n^{\log_27})\approx\Theta(n^{2.81})\),比 \(n^3\) 小

615 分

The following figure shows a depth-first search of a tree. The nodes are numbered in the order in which they are visited. Notice that in a depth-first search a path is followed as deeply as possible until a dead end is reached. At a dead end we back up until we reach a node with an unvisited child, and then we again proceed to go as deep as possible.

35647291081214151316111

The following psuedocode is a simple algorithm for doing a depth-first search. The procedure is called by passing the root at the top level.

void depth_first_tree_search (node v)
{
    node u;
    visit v;
    for (each child u of v)
        depth_first-tree_search( ____________ );
}

(a) (3 分) There is a blank in the above algorithm. Please fill the blank. (b) (3 分) If the number of nodes in the tree is n, what is the time complexity T(n) of this algorithm in terms of big-O notation? (c) (3 分) Is the above algorithm an “inorder tree traversal algorithm”? Why? (d) (3 分) Is the above algorithm a “recursive algorithm”? Why? (e) (3 分) If we do a breadth-first search on the above tree, please draw a figure to number the nodes in the order in which they are visited.

(a) 對 \(v\) 的每個 child \(u\) 遞迴呼叫

u (depth_first_tree_search(u);)

(b) 每個節點恰好被 visit 一次,每條 parent→child 邊恰好被走一次(\(n-1\) 條)

\(T(n)=O(n)\)

(c) 不是。inorder 是「左子樹 → 根 → 右子樹」,根在中間;這個演算法先 visit \(v\),再走各個 child,根在最前面,是 preorder(圖中的編號也是根 1 最先)

這棵樹有節點有三個 child,inorder 只對 binary tree 才有定義

不是(是 preorder traversal)

(d) 是。depth_first_tree_search 的內部又呼叫自己(對 child),把問題化成較小的子樹,空的 child 清單時就停下,所以是 recursive algorithm

是

(e) BFS 一層一層由左到右用 queue 拜訪:根 → 第二層 → 第三層 → 第四層。圖中節點內的數字是 BFS 順序

51314672893101516111241

用 queue:1 入列;取出 1,把 2、8、11 入列;取出 2,把 3、4、7 入列……(此處以 DFS 圖上的節點為準)

712 分

Explain the following terms. (a) (3 分) The 0-1 knapsack problem. (b) (3 分) NP-complete. (c) (3 分) Branch-and-bound algorithm (d) (3 分) Euclid's algorithm

(a) 0-1 knapsack:有 \(n\) 個物品,物品 \(i\) 重 \(w_i\)、價值 \(p_i\),背包容量 \(W\)。每個物品「整個拿或整個不拿」(\(x_i\in\{0,1\}\),不能切開),選出一組使 \(\sum w_ix_i\le W\) 且總價值 \(\sum p_ix_i\) 最大

DP 可解,\(O(nW)\)(pseudo-polynomial);一般情況是 NP-hard。可以切開拿的 fractional knapsack 用 greedy(價值/重量比由高到低)就最佳

(b) NP-complete:決策問題 \(L\) 若 ① \(L\in\text{NP}\)(答案可在 polynomial time 驗證)且 ② 是 NP-hard(NP 中每個問題都能在 polynomial time reduce 到 \(L\)),就是 NP-complete。它們是 NP 中最難的問題;只要有一個能在 polynomial time 解出,P = NP。例:SAT、Hamiltonian cycle、0-1 knapsack 的決策版

(c) Branch-and-bound:用來解最佳化問題的 state-space tree 搜尋:把問題分成子問題(branch),對每個節點算一個 bound(最大化問題用「這個節點底下最好可能達到的值」的上界);若 bound 不比目前已找到的最佳解好,這個節點整棵子樹剪掉(prune),不必展開。通常配 best-first 或 DFS 搜尋,比窮舉快很多

(d) Euclid's algorithm:求最大公因數:\(\gcd(a,b)=\gcd(b,\ a\bmod b)\),\(\gcd(a,0)=a\),反覆取餘數到餘數為 0;時間 \(O(\log\min(a,b))\)

88 分

Suppose you are given an array A of n elements containing only four distinct values 1, 2, 3, and 4. You want to sort the array in ascending order. Please design a linear-time algorithm to sort the array. Please also show the space complexity of your algorithm.

值域只有 4 個,用 counting sort:數每個值出現幾次,再依序寫回

sort4(A[0..n-1]):
  cnt[1..4] = 0
  for i = 0..n-1: cnt[ A[i] ]++            // 掃一遍,O(n)
  p = 0
  for v = 1..4:
      for t = 1..cnt[v]:                   // 寫回 v 共 cnt[v] 次,總共 n 次
          A[p] = v; p++

時間:兩段各掃 \(n\) 個位置,\(O(n)\)

空間:只多了 4 個計數器,\(O(1)\) extra space(原地排)

另一種做法:「荷蘭國旗」式的多指標 in-place partition,同樣 \(O(n)\)、\(O(1)\);若要 stable(元素帶 satellite data),counting sort 要另開 \(O(n)\) 的輸出陣列

時間 \(O(n)\),額外空間 \(O(1)\)

109–115 的詳解也是這樣寫的。

國立臺灣師範大學 109–115 的詳解收錄在付費版;106–115 全年度完整詳解共 309 頁,逐題推導。

購買 · NT$ 850 看師大其他免費詳解

其他年度與考科

同一年的其他科

同一科的其他年度

聯絡我們

題目有錯、詳解看不懂,都歡迎來信

想許願補哪一份、對購買有疑問也可以,收到後會盡快回覆。

william.chou.123123@gmail.com