108 年 國立臺灣大學資訊工程學系碩士班《資料結構與演算法》

📄 試題原卷 免費註冊後即可對照原始考卷 PDF免費註冊

第 1 題10 分

  1. (10%) Let bnb_n be the number of different permutations obtainable by passing the numbers 1,2,3,…,n1, 2, 3, \ldots, n through a stack and deleting in all possible ways.
    (a) Give the recursive formula for bnb_n.
    (b) Give the analytic formula for bnb_n.

登入後即可作答並保存紀錄。

這一題的完整詳解

核心觀念

本題考的是:

  • 堆疊(stack)的後進先出(LIFO)特性;
  • 合法的 push/pop 操作序列;
  • Catalan number(卡特蘭數)的遞迴式與封閉形式。

輸入順序固定為 1,2,…,n1,2,\ldots,n。每個數字依序進入堆疊,但可以在任意時刻刪除(pop)堆疊頂端元素,因此產生不同的輸出排列。

例如 n=3n=3 時,合法排列包括:

123,132,213,231,321123,\quad 132,\quad 213,\quad 231,\quad 321

但 312312 無法產生,因為要先輸出 33,必須先將 1,2,31,2,3 都放入堆疊;此時 33 輸出後,22 必須先於 11 輸出,不可能接著輸出 11。


解題方法

將堆疊操作轉換成括號序列

將「放入堆疊」視為左括號,將「刪除堆疊頂端元素」視為右括號。

由於任何時刻刪除的元素都必須是目前堆疊頂端,因此刪除次數不能超過放入次數。最後必須完成 nn 次放入與 nn 次刪除。

所以,合法操作序列正好對應於長度為 2n2n 的合法括號序列,也就是 Dyck paths。其數量即為第 nn 個 Catalan number。


(a) 遞迴公式

令 bnb_n 表示 nn 個元素可形成的合法堆疊排列數,並定義

b0=1b_0=1

考慮第一個元素與其配對的刪除操作。

在這次刪除之前,堆疊內部可能有 ii 個元素;刪除該元素之後,剩下的操作則包含 n−1−in-1-i 個元素。這兩部分可以獨立形成合法操作,因此共有

bibn−1−ib_i b_{n-1-i}

種方式。

對所有可能的 i=0,1,…,n−1i=0,1,\ldots,n-1 加總,得到:

bn=∑i=0n−1bibn−1−i\boxed{ b_n=\sum_{i=0}^{n-1} b_i b_{n-1-i} }

因此遞迴式為:

b0=1,bn=∑i=0n−1bibn−1−i(n≥1)\boxed{ b_0=1,\qquad b_n=\sum_{i=0}^{n-1} b_i b_{n-1-i}\quad(n\ge 1) }

前幾項為:

b0=1,b1=1,b2=2,b3=5,b4=14b_0=1,\quad b_1=1,\quad b_2=2,\quad b_3=5,\quad b_4=14

(b) 解析公式

這正是 Catalan number 的標準形式,因此:

bn=Cn=1n+1(2nn)\boxed{ b_n=C_n=\frac{1}{n+1}\binom{2n}{n} }

也可以寫成:

bn=(2n)!n!(n+1)!\boxed{ b_n=\frac{(2n)!}{n!(n+1)!} }

公式推導

令生成函數為:

B(x)=∑n=0∞bnxnB(x)=\sum_{n=0}^{\infty}b_nx^n

由遞迴式:

bn=∑i=0n−1bibn−1−ib_n=\sum_{i=0}^{n-1}b_i b_{n-1-i}

可得:

B(x)=1+xB(x)2B(x)=1+xB(x)^2

整理為二次方程式:

xB(x)2−B(x)+1=0xB(x)^2-B(x)+1=0

解得:

B(x)=1±1−4x2xB(x)=\frac{1\pm\sqrt{1-4x}}{2x}
🔒

後續完整解題步驟與【答案】

免費註冊,享三天全站完整詳解閱覽。

免費註冊

第 2 題5 分

  1. (5%) Convert the expression "(a/(c∗(b+d)))/(e−a)∗c(a/(c*(b+d)))/(e-a)*c" into a postfix form.

登入後即可作答並保存紀錄。

這一題的完整詳解

核心觀念

本題考查中序表示式(infix expression)轉後序表示式(postfix expression),也就是將運算子移到其兩個運算元之後。

各運算子的優先順序為:

括號>乘法、除法>加法、減法括號 > 乘法、除法 > 加法、減法

同一優先順序的運算子採由左至右結合,因此:

x/y∗z=(x/y)∗zx/y*z=(x/y)*z

後序表示式不需要括號,因為運算順序已由運算子的位置明確表示。

解題方法

原式為:

ac(b+d)÷(e−a)×c\frac{a}{c(b+d)}\div(e-a)\times c

先依括號與運算子優先順序分解。

第一步:處理括號 (b+d)(b+d)

b+db+d

轉為後序形式:

b d +b\ d\ +

第二步:處理 c∗(b+d)c*(b+d)

將 cc 與前一步結果相乘:

c∗(b+d)c*(b+d)

後序形式為:

c b d + ∗c\ b\ d\ +\ *

第三步:處理 a/(c∗(b+d))a/(c*(b+d))

將 aa 除以前一步結果:

a/[c∗(b+d)]a/[c*(b+d)]

後序形式為:

a c b d + ∗ /a\ c\ b\ d\ +\ *\ /

第四步:處理括號 (e−a)(e-a)

e−ae-a

後序形式為:

e a −e\ a\ -

第五步:處理兩部分相除

原式前半部為:

(ac(b+d))/(e−a)\left(\frac{a}{c(b+d)}\right)/(e-a)

將兩個子運算式依序排列,再放入除法運算子:

a c b d + ∗ / e a − /a\ c\ b\ d\ +\ *\ /\ e\ a\ -\ /

第六步:最後乘以 cc

原式最後為:

🔒

後續完整解題步驟與【答案】

免費註冊,享三天全站完整詳解閱覽。

免費註冊

第 3 題10 分

  1. (10%) Draw the final min-heap tree after the following operations: insert 7, insert 4, insert 3, insert 1, delete min, insert 9, insert 2, insert 5, delete min, delete min.

登入後即可作答並保存紀錄。

這一題的完整詳解

核心觀念

最小堆積(Min-Heap)是一種滿足以下兩項性質的資料結構:

  1. 結構性質(Complete Binary Tree):除最底層外,其餘各層均完全填滿;最底層的節點均緊密由左至右依序排列。
  2. 堆積性質(Min-Heap Property):對於樹中任意非根節點 ii,其鍵值均大於或等於其父節點的鍵值,即:
    A[parent(i)]≤A[i]A[\text{parent}(i)] \leq A[i]
    因此,根節點必定為整棵樹的最小值。

若以 1-based 陣列儲存節點(索引為 ii):

  • 父節點索引:⌊i/2⌋\lfloor i/2 \rfloor
  • 左子節點索引:2i2i
  • 右子節點索引:2i+12i+1

基本操作規則:

  • 插入(Insert):將新節點加入樹的最後一個位置(陣列末端),執行向上調整(Up-Heap / Sift-Up):重複與父節點比較,若小於父節點則進行交換,直到滿足最小堆積性質或已達根節點。
  • 刪除最小值(Delete Min):移除根節點(最小值),將樹中最後一個節點移至根節點位置,執行向下調整(Down-Heap / Sift-Down):比較當前節點與其所有子節點,若大於其中較小的子節點,則與該較小子節點交換,重複此步驟直至滿足最小堆積性質或已達葉節點。

詳細步驟推導

題目給定之操作序列如下:
insert 7 →\to insert 4 →\to insert 3 →\to insert 1 →\to delete min →\to insert 9 →\to insert 2 →\to insert 5 →\to delete min →\to delete min

1. insert 7

  • 將 77 置於根節點。
  • 陣列表示:[7][7]
  • 樹狀結構:
    7
    

2. insert 4

  • 將 44 置於最後位置(索引 2,為節點 77 的左子節點)。
  • 向上調整:4<74 < 7,交換 44 與 77。
  • 陣列表示:[4,7][4, 7]
  • 樹狀結構:
      4
     /
    7
    

3. insert 3

  • 將 33 置於最後位置(索引 3,為節點 44 的右子節點)。
  • 向上調整:3<43 < 4,交換 33 與 44。
  • 陣列表示:[3,7,4][3, 7, 4]
  • 樹狀結構:
      3
     / \
    7   4
    

4. insert 1

  • 將 11 置於最後位置(索引 4,為節點 77 的左子節點),陣列為 [3,7,4,1][3, 7, 4, 1]。
  • 向上調整:
    1. 1<71 < 7,交換 11 與 77,陣列變為 [3,1,4,7][3, 1, 4, 7]。
    2. 繼續與根節點比較:1<31 < 3,交換 11 與 33,陣列變為 [1,3,4,7][1, 3, 4, 7]。
  • 樹狀結構:
        1
       / \
      3   4
     /
    7
    

5. delete min

  • 移除根節點 11,將最後一個元素 77(索引 4)移至根節點,陣列暫時為 [7,3,4][7, 3, 4]。
  • 向下調整:
    • 根節點 77 的子節點為 33 與 44,較小者為 33。
    • 因 7>37 > 3,交換 77 與 33。
    • 交換後節點 77 位於索引 2,已無子節點,調整結束。
  • 陣列表示:[3,7,4][3, 7, 4]
  • 樹狀結構:
      3
     / \
    7   4
    

6. insert 9

  • 將 99 置於最後位置(索引 4,為節點 77 的左子節點)。
  • 向上調整:父節點為 77,因 9>79 > 7,符合最小堆積性質,不需交換。
  • 陣列表示:[3,7,4,9][3, 7, 4, 9]
  • 樹狀結構:
        3
       / \
      7   4
     /
    9
    

7. insert 2

  • 將 22 置於最後位置(索引 5,為節點 77 的右子節點),陣列為 [3,7,4,9,2][3, 7, 4, 9, 2]。
  • 向上調整:
    1. 父節點為 77,因 2<72 < 7,交換 22 與 77,陣列變為 [3,2,4,9,7][3, 2, 4, 9, 7]。
    2. 繼續與父節點(根節點)33 比較,因 2<32 < 3,交換 22 與 33,陣列變為 [2,3,4,9,7][2, 3, 4, 9, 7]。
  • 樹狀結構:
🔒

後續完整解題步驟與【答案】

免費註冊,享三天全站完整詳解閱覽。

免費註冊

第 4 題8 分

  1. (8%) Describe how you can construct a heap of n keys with O(n) complexity. You can simply use n = 15 as an example to explain your idea. (You don't need to prove the complexity.)

登入後即可作答並保存紀錄。

這一題的完整詳解

核心觀念

本題考查「以自底向上的方式建立 Heap」,也就是 Bottom-Up Build-Heap。

以最大堆(max heap)為例,必須滿足:

A[parent(i)]≥A[i]A[\mathrm{parent}(i)] \ge A[i]

陣列表示的完全二元樹中:

  • 第 ii 個節點的父節點為 ⌊i/2⌋\lfloor i/2 \rfloor
  • 左子節點為 2i2i
  • 右子節點為 2i+12i+1
  • i>⌊n/2⌋i>\lfloor n/2\rfloor 的節點全部是葉節點

葉節點本身已經符合 Heap 條件,因此只需從最後一個內部節點開始,反向處理至根節點。


解題方法

建立最大堆的演算法如下:

  1. 將 nn 個鍵值先依序放入完全二元樹。
  2. 從第 ⌊n/2⌋\lfloor n/2\rfloor 個節點開始。
  3. 對每個內部節點執行 sift-down:
    • 比較該節點與兩個子節點。
    • 將較大的子節點與父節點交換。
    • 若交換後仍違反最大堆條件,繼續向下調整。
  4. 處理順序為:
⌊n2⌋,⌊n2⌋−1,…,2,1\left\lfloor\frac n2\right\rfloor, \left\lfloor\frac n2\right\rfloor-1,\ldots,2,1

此方法建立 Heap 的時間複雜度為:

O(n)O(n)

不可使用逐一插入的方式,因為每次插入可能需要向上調整 O(log⁡n)O(\log n),總複雜度會是 O(nlog⁡n)O(n\log n)。


以 n=15n=15 為例

假設原始陣列為:

[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15][1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

其完全二元樹如下:

                    1
              /           \
             2             3
          /     \       /     \
         4       5     6       7
        / \     / \   / \     / \
       8   9  10 11 12 13  14 15

因為:

⌊152⌋=7\left\lfloor\frac{15}{2}\right\rfloor=7

所以從節點 77 開始,依序處理節點 7,6,5,4,3,2,17,6,5,4,3,2,1。

處理節點 7

節點 77 的子節點為 14,1514,15,最大值為 1515,交換:

節點 7:7 → 15
節點 15:15 → 7

處理節點 6

節點 66 的子節點為 12,1312,13,交換較大的 1313:

節點 6:6 → 13
節點 13:13 → 6

處理節點 5

節點 55 的子節點為 10,1110,11,交換較大的 1111:

節點 5:5 → 11
節點 11:11 → 5

處理節點 4

節點 44 的子節點為 8,98,9,交換較大的 99:

節點 4:4 → 9
節點 9:9 → 4

此時陣列為:

[1,2,3,9,11,13,15,8,4,10,5,12,6,14,7][1,2,3,9,11,13,15,8,4,10,5,12,6,14,7]

處理節點 3

節點 33 的子節點為 13,1513,15,先與較大的 1515 交換:

[1,2,15,9,11,13,3,8,4,10,5,12,6,14,7][1,2,15,9,11,13,3,8,4,10,5,12,6,14,7]

交換後,節點 77 的子節點為 14,714,7,仍需向下調整,與 1414 交換:

[1,2,15,9,11,13,14,8,4,10,5,12,6,3,7][1,2,15,9,11,13,14,8,4,10,5,12,6,3,7]

處理節點 2

節點 22 的子節點為 9,119,11,與 1111 交換:

[1,11,15,9,2,13,14,8,4,10,5,12,6,3,7][1,11,15,9,2,13,14,8,4,10,5,12,6,3,7]

節點 55 的子節點為 10,510,5,再與 1010 交換:

[1,11,15,9,10,13,14,8,4,2,5,12,6,3,7][1,11,15,9,10,13,14,8,4,2,5,12,6,3,7]

處理根節點 1

🔒

後續完整解題步驟與【答案】

免費註冊,享三天全站完整詳解閱覽。

免費註冊

第 5 題20 分

  1. (20%) Quicksort is a fast and commonly used comparison-based sorting algorithm. Below you can find a version of quicksort algorithm in pseudo code format.

QUICKSORT(A, p, r)
1 if p < r
2 q = PARTITION(A, p, r)
3 QUICKSORT(A, p, q - 1)
4 QUICKSORT(A, q + 1, r)

PARTITION(A, p, r)
1 x = A[r]
2 i = p - 1
3 for j = p to r - 1
4 if A[j] ≤ x
5 i = i + 1
6 exchange A[i] with A[j]
7 exchange A[i + 1] with A[r]
8 return i + 1

(a) (6%) True or false:
(1) The output of QUICKSORT() above is a non-increasing sorted sequence. (2%)
(2) The QUICKSORT() above is a stable sorting algorithm. (2%)
(3) The QUICKSORT() above is an in-place sorting algorithm. (2%)

(b) (4%) The given version of QUICKSORT above cannot efficiently process the cases where in the input array there are a large number of repeated elements. Analyze the worst-case running time which occurs when all n keys in the input array A are identical. Please give it in big-O notation in terms of n.

(c) (10%) To address the previously mentioned problematic case, we will now develop a new partition algorithm PARITITIONTHREE() that separates the input keys into three groups, the ones that are smaller than, that are identical to, and that are larger than the pivot key x. The return values q1 and q2 represent the indices of the first and the last keys of the group that equals the pivot key, respectively. Fill the blanks (A), (B), (C) in PARITIONTHREE() below to complete the implementation, such that QUICKSORTTHREE() runs in O(n)-time when the input array has all n elements identical.

QUICKSORTTHREE(A, p, r)
1 if p < r
2 (q1, q2) = PARTITIONTHREE(A, p, r)
3 QUICKSORTTHREE(A, p, q1 - 1)
4 QUICKSORTTHREE(A, q2 + 1, r)

PARTITIONTHREE(A, p, r)
1 x = A[r]
2 q1 = p
3 q2 = r
4 j = p
5 while j ≤ q2
6 if A[j] < x
7 exchange A[j] with A[q1]
8 // (A)
9 j = j + 1
10 elseif A[j] > x
11 exchange A[j] with A[q2]
12 // (B)
13 else
14 // (C)
15 return (q1, q2)

登入後即可作答並保存紀錄。

這一題的完整詳解

(a) 觀念是非題

(1) False
PARTITION 以基準值 x=A[r]x = A[r] 為界,將小於等於 xx 的元素移至左側,大於 xx 的元素移至右側,並置中基準值。經過遞迴排序後,陣列呈現由小到大的非遞減序列(non-decreasing sorted sequence,即 A[1]≤A[2]≤⋯≤A[n]A[1] \le A[2] \le \cdots \le A[n]),而非由大到小的非遞增序列(non-increasing sorted sequence)。

(2) False
本題給定的 Lomuto partition 並不具備穩定性(stable sorting)。
例如考慮輸入陣列 A=[3a,3b,1]A = [3_a, 3_b, 1],基準值 x=A[3]=1x = A[3] = 1:

  • 走訪 j=1,2j = 1, 2 時,元素 3a,3b3_a, 3_b 皆大於 11,條件 A[j]≤xA[j] \le x 皆不成立,指標 ii 維持在 p−1=0p - 1 = 0。
  • 迴圈結束後執行第 7 行 exchange A[i + 1] with A[r],即交換 A[1]A[1] 與 A[3]A[3],陣列變為 [1,3b,3a][1, 3_b, 3_a]。
    原本在前的 3a3_a 被換到了 3b3_b 的後方,改變了相同鍵值的相對次序,故演算法不穩定。

(3) True
原地排序演算法(in-place sorting algorithm)是指除了輸入陣列本身之外,僅使用常數階 O(1)O(1) 的輔助記憶體空間來重排元素(遞迴呼叫堆疊所需的空間至多為 O(n)O(n),符合標準定義)。本題的 PARTITION 僅在原陣列內做元素交換,額外變數僅有 x,i,jx, i, j 等常數個暫存變數,故為原地演算法。


(b) 全部元素皆相同時的最壞時間複雜度

當陣列中所有 nn 個鍵值皆相同(設皆等於常數 cc)時:

  1. 基準值 x=A[r]=cx = A[r] = c。
  2. 在 PARTITION(A, p, r) 中,jj 從 pp 走訪至 r−1r - 1。對每一個元素而言,A[j]=c≤c=xA[j] = c \le c = x 恆成立,因此條件 if A[j] ≤ x 每次皆成立。
  3. 迴圈共執行 n−1n - 1 次,每次皆使 ii 遞增 1 並執行交換,結束時 i=r−1i = r - 1。
  4. 第 7 行將 A[i+1]=A[r]A[i + 1] = A[r] 與 A[r]A[r] 交換,並於第 8 行回傳分割索引 q=i+1=rq = i + 1 = r。

此時切分結果極度不均勻:

  • 左側子問題 QUICKSORT(A, p, q - 1) 的長度為 (r−1)−p+1=n−1(r - 1) - p + 1 = n - 1。
  • 右側子問題 QUICKSORT(A, q + 1, r) 的長度為 r−(r+1)+1=0r - (r + 1) + 1 = 0(空陣列)。

分割過程耗時 Θ(n)\Theta(n),故時間複雜度的遞迴關係式為:
T(n)=T(n−1)+T(0)+Θ(n)=T(n−1)+Θ(n)T(n) = T(n - 1) + T(0) + \Theta(n) = T(n - 1) + \Theta(n)

將遞迴式展開求和:
T(n)=∑k=1nΘ(k)=Θ(n2)T(n) = \sum_{k=1}^n \Theta(k) = \Theta(n^2)

以 Big-OO 符號表示,其最壞情況執行時間為 O(n2)O(n^2)。


(c) 三路切分(3-way Partitioning)演算法實作

此演算法採用荷蘭國旗三路切分法,在 while j ≤ q2 迴圈中維持以下區間不變量(Loop Invariant):

  • A[p…q1−1]A[p \dots q1 - 1]:小於基準值的元素(<x< x)
  • A[q1…j−1]A[q1 \dots j - 1]:等於基準值的元素(==x== x)
  • A[j…q2]A[j \dots q2]:尚未檢查的未處理元素
  • A[q2+1…r]A[q2 + 1 \dots r]:大於基準值的元素(>x> x)
🔒

後續完整解題步驟與【答案】

免費註冊,享三天全站完整詳解閱覽。

免費註冊

第 6 題13 分

  1. (13%) When implementing a hash table, one of the commonly used collision resolution methods is open addressing. Let kk be the key, and mm be the size of the hash table. Assume each table entry can hold one key.
    (a) (3%) The simplest open addressing method is called linear probing, where if a slot is already occupied, the following slots are "probed" sequentially. Assume an auxiliary hash function h′(k)=k mod mh'(k) = k \bmod m. Please give the hash function h(k,i)h(k, i) of linear probing with the given auxiliary function, where ii is the number of times the hash table has been probed with this key (and thus starting from 0).
    (b) (5%) Linear probing is easy to implement but suffers from the problem of primary clustering. A more complex open addressing method which can mitigate this problem is double hashing, using a hash function in the form of h(k,i)=(h1(k)+i⋅h2(k)) mod mh(k, i) = (h_1(k) + i \cdot h_2(k)) \bmod m, with two auxiliary hash functions h1(k)h_1(k) and h2(k)h_2(k). ii is the number of times the hash table has been probed with key kk. Assume two auxiliary hash functions h1(k)=k mod 16h_1(k) = k \bmod 16, h2(k)=1+(k mod 15)h_2(k) = 1 + (k \bmod 15), and m=16m = 16. Show the final hash table content after inserting all of the following keys to an initially empty hash table in the given order: {16,3,35,67,51,1,15,31,19,17}\{16, 3, 35, 67, 51, 1, 15, 31, 19, 17\}.
    (c) (5%) Prof. Alpha proposes a different double hashing method, using two auxiliary hash functions h1(k)=k mod 16h_1(k) = k \bmod 16, h2(k)=2(k mod 8)h_2(k) = 2(k \bmod 8), respectively. Assume the table size m=16m = 16. Use an example to briefly explain how Prof. Alpha's method is problematic.

登入後即可作答並保存紀錄。

這一題的完整詳解

核心觀念

Open addressing 將所有資料直接存放在 hash table 中;發生碰撞時,利用 probe sequence 依序尋找下一個空槽。

一般形式為:

h(k,i)h(k,i)

其中:

  • kk:鍵值
  • ii:探測次數,從 00 開始
  • mm:hash table 大小
  • h(k,0)h(k,0):第一次探測的位置

雙重雜湊的形式為:

h(k,i)=(h1(k)+i⋅h2(k)) mod mh(k,i)=\bigl(h_1(k)+i\cdot h_2(k)\bigr)\bmod m

其中 h2(k)h_2(k) 是每次探測前進的步長。


(a)Linear Probing

線性探測每次向後移動一格,因此:

h(k,i)=(h′(k)+i) mod mh(k,i)=\bigl(h'(k)+i\bigr)\bmod m

題目給定:

h′(k)=k mod mh'(k)=k\bmod m

代入可得:

h(k,i)=((k mod m)+i) mod m\boxed{h(k,i)=\bigl((k\bmod m)+i\bigr)\bmod m}

由模運算性質,也可寫成:

h(k,i)=(k+i) mod m\boxed{h(k,i)=(k+i)\bmod m}

當 i=0i=0 時,探測原始 hash 位置;若該位置被占用,則依序探測下一格。


(b)Double Hashing

題目給定:

h1(k)=k mod 16h_1(k)=k\bmod 16 h2(k)=1+(k mod 15)h_2(k)=1+(k\bmod 15) h(k,i)=(h1(k)+i⋅h2(k)) mod 16h(k,i)=\bigl(h_1(k)+i\cdot h_2(k)\bigr)\bmod 16

依照題目順序插入各鍵值。

逐一插入

鍵值 kkh1(k)h_1(k)h2(k)h_2(k)探測位置最終位置
161600220000
3333443333
353533663,93,999
676733883,113,111111
515133773,103,101010
1111221111
151515151115151515
313115152215,1,3,515,1,3,555
191933553,83,888
171711331,41,444

以 3131 為例:

h1(31)=31 mod 16=15h_1(31)=31\bmod16=15 h2(31)=1+(31 mod 15)=1+1=2h_2(31)=1+(31\bmod15)=1+1=2

探測序列為:

h(31,0)=(15+0⋅2) mod 16=15h(31,1)=(15+1⋅2) mod 16=1h(31,2)=(15+2⋅2) mod 16=3h(31,3)=(15+3⋅2) mod 16=5\begin{aligned} h(31,0)&=(15+0\cdot2)\bmod16=15\\ h(31,1)&=(15+1\cdot2)\bmod16=1\\ h(31,2)&=(15+2\cdot2)\bmod16=3\\ h(31,3)&=(15+3\cdot2)\bmod16=5 \end{aligned}

位置 15,1,315,1,3 均已占用,因此放入位置 55。

最終 hash table

索引01234567
內容161空31731空空
索引89101112131415
內容19355167空空空15

因此:

[16, 1, ∅, 3, 17, 31, ∅, ∅, 19, 35, 51, 67, ∅, ∅, ∅, 15]\boxed{ [16,\ 1,\ \varnothing,\ 3,\ 17,\ 31,\ \varnothing,\ \varnothing,\ 19,\ 35,\ 51,\ 67,\ \varnothing,\ \varnothing,\ \varnothing,\ 15] }

(c)Prof. Alpha 方法的問題

題目給定:

h1(k)=k mod 16h_1(k)=k\bmod16 h2(k)=2(k mod 8)h_2(k)=2(k\bmod8)

雙重雜湊為:

h(k,i)=(h1(k)+i⋅h2(k)) mod 16h(k,i)=\bigl(h_1(k)+i\cdot h_2(k)\bigr)\bmod16

此方法的關鍵問題是:h2(k)h_2(k) 不一定與 m=16m=16 互質。

若步長與 table 大小的最大公因數大於 11,探測序列只能訪問部分槽位,無法走遍整張表。

具體例子:k=16k=16

h1(16)=16 mod 16=0h_1(16)=16\bmod16=0
🔒

後續完整解題步驟與【答案】

免費註冊,享三天全站完整詳解閱覽。

免費註冊

第 7 題6 分

  1. (6%) True or false:
    (a) (2%) The Dijkstra's algorithm (single run) solves the single-source shortest path problem with positive, zero, or negative edge weights, if there is no negative cycle.
    (b) (2%) The Bellman-Ford algorithm (single run) solves the all-pairs shortest path problem with non-negative edge weights.
    (c) (2%) The Floyd-Warshall algorithm (single run) solves the all-pairs shortest path with positive, zero, or negative edge weights, even if there are negative cycles.

登入後即可作答並保存紀錄。

這一題的完整詳解

核心觀念

本題考查三種最短路徑演算法的適用範圍:

  • Dijkstra:解單源最短路徑,但要求所有邊權重皆非負。
  • Bellman-Ford:解單源最短路徑,可處理負權重;也能偵測負環。
  • Floyd-Warshall:解全點對最短路徑,可處理負權重,但不能在存在負環時定義有限的最短路徑。

若圖中存在從 ss 到 tt 的負環,沿著負環繞行次數越多,路徑成本便能無限下降:

dist⁡(s,t)=−∞\operatorname{dist}(s,t)=-\infty

因此「存在負環時仍能求得全點對最短路徑」通常是不成立的。


解題方法

逐一檢查每個演算法的:

  1. 解決問題類型:單源或全點對。
  2. 邊權重限制:是否允許負邊。
  3. 負環影響:是否仍存在定義良好的最短路徑。

選項分析

(a) 錯誤

Dijkstra 的確是解單源最短路徑問題,但其正確性的關鍵條件是:

w(u,v)≥0w(u,v)\ge 0

也就是所有邊權重必須非負。原因是 Dijkstra 採用貪心法,一旦選出目前距離最小的頂點,就認定其最短距離已經確定。若存在負邊,之後仍可能透過其他頂點找到更短的路徑,導致先前確定的結果錯誤。

例如有以下邊:

s→u:1,s→v:4,v→u:−5s\to u:1,\qquad s\to v:4,\qquad v\to u:-5

從 ss 出發時:

  • 目前 d(u)=1d(u)=1
  • 目前 d(v)=4d(v)=4

Dijkstra 會先確定 uu 的距離為 11。但實際上存在路徑

s→v→us\to v\to u

其成本為:

4+(−5)=−14+(-5)=-1

因此真正的最短距離是 −1-1,不是 11。此圖沒有負環,仍足以顯示 Dijkstra 不能處理一般負邊。

所以「沒有負環」並不足以保證 Dijkstra 正確,還必須要求所有邊權重非負。


(b) 錯誤

Bellman-Ford 解決的是單源最短路徑問題,即給定一個來源頂點 ss,求:

dist⁡(s,v)\operatorname{dist}(s,v)

對所有頂點 vv 的最短距離。

它不能在單次執行中直接求出任意兩點 u,vu,v 之間的最短距離:

dist⁡(u,v)\operatorname{dist}(u,v)

因此 Bellman-Ford 單次執行不是全點對最短路徑演算法。若要使用 Bellman-Ford 求全點對最短路徑,必須對每個頂點分別執行一次,總共執行 ∣V∣|V| 次。

Bellman-Ford 的基本作法是反覆對所有邊進行鬆弛:

d[v]←min⁡(d[v],d[u]+w(u,v))d[v]\leftarrow \min\bigl(d[v],d[u]+w(u,v)\bigr)

最多進行 ∣V∣−1|V|-1 輪;若第 ∣V∣|V| 輪仍可鬆弛,代表存在可達負環。

非負邊權只會讓問題更容易,但不會改變 Bellman-Ford 的問題類型。因此本選項錯在把單源演算法說成全點對演算法。


(c) 錯誤

Floyd-Warshall 是全點對最短路徑演算法,且能處理:

  • 正權重邊
  • 零權重邊
  • 負權重邊

其動態規劃遞迴式為:

🔒

後續完整解題步驟與【答案】

免費註冊,享三天全站完整詳解閱覽。

免費註冊

第 8 題8 分

  1. (8%) Given a directed graph G where vertex u (in G) has at least one path to any other vertex (in G), the following pseudocode is designed to output an acyclic graph. However, in Lines 8, 10, 11, and 14, each of A, B, C, and D should be 0, 1, or 2. Write down the correct values of A, B, C, and D so that the pseudocode can successfully output an acyclic graph.
1  Cycle-Removal(G,u)
2    Initialize S as a stack
3    Label all vertices in G as Type-0
4    Label u as Type-1
5    S.push(u)
6    while S is not empty
7      v = the top vertex of S // Comment: not S.pop() here
8      if v has a Type-A neighbor w in G
9        Remove (v,w) from G
10     else if v has a Type-B neighbor w in G
11       Label w as Type-C
12       S.push(w)
13     else
14       Label v as Type-D
15       S.pop()
16     end if
17 end while
18 output G

登入後即可作答並保存紀錄。

這一題的完整詳解

核心觀念

本題考查:

  • 深度優先搜尋(DFS)的三種頂點狀態。
  • DFS 堆疊中「尚未完成處理」的頂點。
  • 有向圖中的回邊(back edge)。
  • 移除所有回邊即可消除有向環。

三種型態可解讀為:

  • Type-0:尚未拜訪。
  • Type-1:已拜訪但尚未完成,仍在 DFS 堆疊中。
  • Type-2:已完成處理,已從 DFS 堆疊移除。

若目前處理頂點為 vv:

  • 邊 (v,w)(v,w) 若指向 Type-1 頂點,表示形成回邊,可能造成有向環。
  • 邊 (v,w)(v,w) 若指向 Type-0 頂點,表示發現新頂點,必須繼續 DFS。
  • 當 vv 沒有尚未處理的 Type-0 鄰點時,便完成 vv,標記為 Type-2。

解題方法

1. 判斷 Line 8 的 Type-A

if v has a Type-A neighbor w in G
  Remove (v,w) from G

要使輸出圖為無環圖,必須移除造成循環的邊。

在 DFS 中,從目前頂點 vv 指向仍在搜尋路徑上的頂點 ww,即:

v→w,w 為 Type-1v \to w,\qquad w\text{ 為 Type-1}

這種邊稱為回邊。它可能直接形成循環,因此應將其移除。

所以:

A=1A=1

若 A=0A=0,會刪除前往尚未拜訪頂點的邊,可能破壞必要的搜尋邊,卻沒有針對循環本身處理。

若 A=2A=2,會刪除指向已完成頂點的邊。這類邊不代表目前 DFS 路徑上的循環,不應作為移除對象。


2. 判斷 Line 10 的 Type-B

else if v has a Type-B neighbor w in G
  Label w as Type-C
  S.push(w)

當 vv 沒有 Type-1 鄰點時,應尋找尚未拜訪的鄰點,繼續進行 DFS。

尚未拜訪的頂點是 Type-0,因此:

B=0B=0

找到 Type-0 鄰點 ww 後,必須將它標記為「已發現但尚未完成」,也就是 Type-1,接著推入堆疊。

因此:

C=1C=1

若 C=0C=0,ww 仍會被視為未拜訪,可能重複推入堆疊。

若 C=2C=2,則會錯誤地把尚未處理的頂點標記為已完成,破壞 DFS 狀態判斷。


3. 判斷 Line 14 的 Type-D

else
  Label v as Type-D
  S.pop()

當 vv 已經沒有 Type-1 鄰點,也沒有 Type-0 鄰點時,代表 vv 的所有可處理鄰點都已處理完成。此時應結束 vv 的 DFS 處理,將它標記為 Type-2,再從堆疊移除。

因此:

D=2D=2

Type-2 表示該頂點已完成 DFS。之後若其他頂點指向它,這條邊不會形成目前搜尋路徑上的回邊。


正確的完整流程

代入後,程式碼的關鍵部分為:

🔒

後續完整解題步驟與【答案】

免費註冊,享三天全站完整詳解閱覽。

免費註冊

第 9 題10 分

  1. (10%) At 9am, 14 ships are leaving for the other side as shown below, where the English alphabets mean the types of those ships. For safety reasons, each ship can only stop at a pier having the same alphabet, and, if the routes of two ships cross each other, one ship needs to wait 15 minutes before leaving.

DFADBDCEBEAGCFpier
river
ship EFBEGECAEBDABD
index number
1 2 3 4 5 6 7 8 9 10 11 12 13 14

(a) (4%) Write down the maximum number of ships which can leave at 9am.
(b) (6%) Following (a), write down the index numbers (between 1 and 14) of the ships which can leave at 9am.

登入後即可作答並保存紀錄。

這一題的完整詳解

核心觀念

本題考查動態規劃(Dynamic Programming)​中的經典問題:最長共同子序列(Longest Common Subsequence, LCS),在幾何與排程上的應用(如經典的河流兩岸不交叉航線 / 橋樑問題)。

  1. 問題模型分析:

    • 設河流北岸的泊位序列為 PP(長度為 14),南岸的船隻序列為 SS(長度為 14)。
    • 停靠限制:每一艘船隻只能停靠在字母相同的泊位,即若第 jj 艘船停靠在第 ii 個泊位,必須滿足 S[j]=P[i]S[j] = P[i]。
    • 航線不交叉限制:設有兩艘船隻 j1,j2j_1, j_2(不妨設 j1<j2j_1 < j_2)同時於上午 9 點出發,分別駛向泊位 i1,i2i_1, i_2。為使兩條航線在平面上互不交叉且不停靠同一泊位,其目標泊位索引必須滿足 i1<i2i_1 < i_2。
    • 等價轉換:
      選取最多可在上午 9 點同時出航的船隻集合,等價於在 SS 與 PP 中各挑選一組長度相同且索引嚴格遞增的子序列 j1<j2<⋯<jkj_1 < j_2 < \dots < j_k 與 i1<i2<⋯<iki_1 < i_2 < \dots < i_k,使得對應位置的字元皆相同(S[jr]=P[ir]S[j_r] = P[i_r])。此即為求序列 PP 與 SS 的最長共同子序列(LCS),最大船隻數即為 LCS 之長度。
  2. LCS 動態規劃狀態定義與轉移:
    定義 DP[i][j]DP[i][j] 為泊位前綴 P[1…i]P[1 \dots i] 與船隻前綴 S[1…j]S[1 \dots j] 的 LCS 長度。

    DP[i][j]={0,若 i=0 或 j=0DP[i−1][j−1]+1,若 P[i]=S[j]max⁡(DP[i−1][j], DP[i][j−1]),若 P[i]≠S[j]DP[i][j] = \begin{cases} 0, & \text{若 } i=0 \text{ 或 } j=0 \\ DP[i-1][j-1] + 1, & \text{若 } P[i] = S[j] \\ \max(DP[i-1][j],\, DP[i][j-1]), & \text{若 } P[i] \ne S[j] \end{cases}

詳細計算與推導

給定兩岸序列:

  • 泊位序列(索引 1 至 14):
    P=⟨D1,F2,A3,D4,B5,D6,C7,E8,B9,E10,A11,G12,C13,F14⟩P = \langle \text{D}_1, \text{F}_2, \text{A}_3, \text{D}_4, \text{B}_5, \text{D}_6, \text{C}_7, \text{E}_8, \text{B}_9, \text{E}_{10}, \text{A}_{11}, \text{G}_{12}, \text{C}_{13}, \text{F}_{14} \rangle
  • 船隻序列(索引 1 至 14):
    S=⟨E1,F2,B3,E4,G5,E6,C7,A8,E9,B10,D11,A12,B13,D14⟩S = \langle \text{E}_1, \text{F}_2, \text{B}_3, \text{E}_4, \text{G}_5, \text{E}_6, \text{C}_7, \text{A}_8, \text{E}_9, \text{B}_{10}, \text{D}_{11}, \text{A}_{12}, \text{B}_{13}, \text{D}_{14} \rangle

(a) 求最大同時出航船隻數

🔒

後續完整解題步驟與【答案】

免費註冊,享三天全站完整詳解閱覽。

免費註冊

第 10 題10 分

  1. (10%) The goal of this problem is to transform the following sequence of shapes into another sequence of shapes so that the total cost is minimized.

—[Square]—[Circle]—[Triangle]—[Square]—[Triangle]—[Square]—[Triangle]—[Square]—[Circle]—[Triangle]—
(即:□ — ○ — ▷ — □ — ▷ — □ — ▷ — □ — ○ — ▷)

The rules of transformation are shown below. For example, if you do not replace anything, the total cost is 6 + 3 + 2 + 6 + 2 + 6 + 2 + 6 + 3 + 2 = 38. If you replace the last two shapes (circle and triangle) by the rule #3, the total cost is 6 + 3 + 2 + 6 + 2 + 6 + 2 + 6 + 4 = 37. Note that you can choose not to replace a shape if the total cost can be minimized. Also, a rule of transformation can be applied more than once.

shapecost
□6
○3
▷2
rule of transformationpatterncost before transformationcost after transformation
#1□ — ○9 (6+3)7
#2□ — ▷8 (6+2)7
#3○ — ▷5 (3+2)4
#4▷ — □8 (2+6)6
#5□ — ○ — ▷11 (6+3+2)8
#6□ — ▷ — □14 (6+2+6)12
#7▷ — □ — ▷10 (2+6+2)7

(a) (4%) Write down the minimum total cost after transforming the given sequence.
(b) (6%) Following (a), write down the applied rules of transformation from left of the sequence to right of the sequence.

登入後即可作答並保存紀錄。

這一題的完整詳解

核心觀念

本題的核心為一維動態規劃(1D Dynamic Programming, DP)​中的序列分割問題(Sequence Segmentation Problem)。

  1. 最佳子結構(Optimal Substructure):
    長度為 ii 的前綴序列之最小成本,取決於更短前綴序列的最佳成本加上最後一段形狀(不替換或套用匹配的轉換規則)的花費。
  2. 重疊子問題(Overlapping Subproblems):
    計算後續位置的最小成本時,會重複查詢相同前綴的最優解,適合建立一維表格由左至右遞推計算。

解題方法

1. 符號與規則整理

  • 形狀原始成本(Cost Before Transformation):

    • 正方形 □=6\text{□} = 6
    • 圓形 ○=3\text{○} = 3
    • 三角形 ▷=2\text{▷} = 2
  • 轉換規則(Transformation Rules):

    • Rule #1:(□,○)(\text{□}, \text{○}),成本 6+3=9→76 + 3 = 9 \to 7(節省 2)
    • Rule #2:(□,▷)(\text{□}, \text{▷}),成本 6+2=8→76 + 2 = 8 \to 7(節省 1)
    • Rule #3:(○,▷)(\text{○}, \text{▷}),成本 3+2=5→43 + 2 = 5 \to 4(節省 1)
    • Rule #4:(▷,□)(\text{▷}, \text{□}),成本 2+6=8→62 + 6 = 8 \to 6(節省 2)
    • Rule #5:(□,○,▷)(\text{□}, \text{○}, \text{▷}),成本 6+3+2=11→86 + 3 + 2 = 11 \to 8(節省 3)
    • Rule #6:(□,▷,□)(\text{□}, \text{▷}, \text{□}),成本 6+2+6=14→126 + 2 + 6 = 14 \to 12(節省 2)
    • Rule #7:(▷,□,▷)(\text{▷}, \text{□}, \text{▷}),成本 2+6+2=10→72 + 6 + 2 = 10 \to 7(節省 3)
  • 待轉換序列(共 10 個圖形):
    S=(S1,S2,…,S10)=(□,○,▷,□,▷,□,▷,□,○,▷)S = (S_1, S_2, \dots, S_{10}) = (\text{□}, \text{○}, \text{▷}, \text{□}, \text{▷}, \text{□}, \text{▷}, \text{□}, \text{○}, \text{▷})

    • 原始總成本 =6+3+2+6+2+6+2+6+3+2=38= 6 + 3 + 2 + 6 + 2 + 6 + 2 + 6 + 3 + 2 = 38。

2. 定義 DP 狀態與轉移方程式

定義 DP[i]DP[i] 為將前綴序列 S[1…i]S[1 \dots i] 轉換後的最小總成本(0≤i≤100 \le i \le 10),基礎狀態為 DP[0]=0DP[0] = 0。

轉移方程式為:
DP[i]=min⁡{DP[i−1]+cost(S[i])(不替換第 i 個形狀)DP[i−2]+rule_cost(S[i−1…i])(若匹配長度為 2 的規則)DP[i−3]+rule_cost(S[i−2…i])(若匹配長度為 3 的規則)DP[i] = \min \begin{cases} DP[i-1] + \text{cost}(S[i]) & \text{(不替換第 } i \text{ 個形狀)} \\ DP[i-2] + \text{rule\_cost}(S[i-1 \dots i]) & \text{(若匹配長度為 2 的規則)} \\ DP[i-3] + \text{rule\_cost}(S[i-2 \dots i]) & \text{(若匹配長度為 3 的規則)} \end{cases}


3. 逐步推導計算

  • i=1i = 1:S[1]=□S[1] = \text{□}
    DP[1]=DP[0]+6=6DP[1] = DP[0] + 6 = 6

  • i=2i = 2:S[1…2]=(□,○)S[1 \dots 2] = (\text{□}, \text{○})

    • 不替換:DP[1]+3=6+3=9DP[1] + 3 = 6 + 3 = 9
    • 套用 Rule #1 (□,○)(\text{□}, \text{○}):DP[0]+7=7DP[0] + 7 = 7
      DP[2]=min⁡(9,7)=7DP[2] = \min(9, 7) = 7
  • i=3i = 3:S[1…3]=(□,○,▷)S[1 \dots 3] = (\text{□}, \text{○}, \text{▷})

    • 不替換:DP[2]+2=7+2=9DP[2] + 2 = 7 + 2 = 9
    • 套用 Rule #3 於 S[2…3]=(○,▷)S[2 \dots 3] = (\text{○}, \text{▷}):DP[1]+4=6+4=10DP[1] + 4 = 6 + 4 = 10
    • 套用 Rule #5 於 S[1…3]=(□,○,▷)S[1 \dots 3] = (\text{□}, \text{○}, \text{▷}):DP[0]+8=8DP[0] + 8 = 8
      DP[3]=min⁡(9,10,8)=8DP[3] = \min(9, 10, 8) = 8
  • i=4i = 4:S[1…4]=(□,○,▷,□)S[1 \dots 4] = (\text{□}, \text{○}, \text{▷}, \text{□})

    • 不替換:DP[3]+6=8+6=14DP[3] + 6 = 8 + 6 = 14
    • 套用 Rule #4 於 S[3…4]=(▷,□)S[3 \dots 4] = (\text{▷}, \text{□}):DP[2]+6=7+6=13DP[2] + 6 = 7 + 6 = 13
      DP[4]=min⁡(14,13)=13DP[4] = \min(14, 13) = 13
  • i=5i = 5:S[1…5]=(□,○,▷,□,▷)S[1 \dots 5] = (\text{□}, \text{○}, \text{▷}, \text{□}, \text{▷})

    • 不替換:DP[4]+2=13+2=15DP[4] + 2 = 13 + 2 = 15
    • 套用 Rule #2 於 S[4…5]=(□,▷)S[4 \dots 5] = (\text{□}, \text{▷}):DP[3]+7=8+7=15DP[3] + 7 = 8 + 7 = 15
    • 套用 Rule #7 於 S[3…5]=(▷,□,▷)S[3 \dots 5] = (\text{▷}, \text{□}, \text{▷}):DP[2]+7=7+7=14DP[2] + 7 = 7 + 7 = 14
      DP[5]=min⁡(15,15,14)=14DP[5] = \min(15, 15, 14) = 14
  • i=6i = 6:S[1…6]=(□,○,▷,□,▷,□)S[1 \dots 6] = (\text{□}, \text{○}, \text{▷}, \text{□}, \text{▷}, \text{□})

    • 不替換:DP[5]+6=14+6=20DP[5] + 6 = 14 + 6 = 20
    • 套用 Rule #4 於 S[5…6]=(▷,□)S[5 \dots 6] = (\text{▷}, \text{□}):DP[4]+6=13+6=19DP[4] + 6 = 13 + 6 = 19
    • 套用 Rule #6 於 S[4…6]=(□,▷,□)S[4 \dots 6] = (\text{□}, \text{▷}, \text{□}):DP[3]+12=8+12=20DP[3] + 12 = 8 + 12 = 20
      DP[6]=min⁡(20,19,20)=19DP[6] = \min(20, 19, 20) = 19
  • i=7i = 7:S[1…7]=(□,○,▷,□,▷,□,▷)S[1 \dots 7] = (\text{□}, \text{○}, \text{▷}, \text{□}, \text{▷}, \text{□}, \text{▷})

    • 不替換:DP[6]+2=19+2=21DP[6] + 2 = 19 + 2 = 21
    • 套用 Rule #2 於 S[6…7]=(□,▷)S[6 \dots 7] = (\text{□}, \text{▷}):DP[5]+7=14+7=21DP[5] + 7 = 14 + 7 = 21
    • 套用 Rule #7 於 S[5…7]=(▷,□,▷)S[5 \dots 7] = (\text{▷}, \text{□}, \text{▷}):DP[4]+7=13+7=20DP[4] + 7 = 13 + 7 = 20
      DP[7]=min⁡(21,21,20)=20DP[7] = \min(21, 21, 20) = 20
  • i=8i = 8:S[1…8]=(□,○,▷,□,▷,□,▷,□)S[1 \dots 8] = (\text{□}, \text{○}, \text{▷}, \text{□}, \text{▷}, \text{□}, \text{▷}, \text{□})

    • 不替換:DP[7]+6=20+6=26DP[7] + 6 = 20 + 6 = 26
    • 套用 Rule #4 於 S[7…8]=(▷,□)S[7 \dots 8] = (\text{▷}, \text{□}):DP[6]+6=19+6=25DP[6] + 6 = 19 + 6 = 25
    • 套用 Rule #6 於 S[6…8]=(□,▷,□)S[6 \dots 8] = (\text{□}, \text{▷}, \text{□}):DP[5]+12=14+12=26DP[5] + 12 = 14 + 12 = 26
      DP[8]=min⁡(26,25,26)=25DP[8] = \min(26, 25, 26) = 25
🔒

後續完整解題步驟與【答案】

免費註冊,享三天全站完整詳解閱覽。

免費註冊

其他考古題