115 年 國立臺灣大學資料科學碩士學位學程《資料結構與演算法》

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

第 1 題4 分

  1. (4 points) Let SS be a stack containing n+1n+1 coefficients a0,a1,…,ana_0, a_1, \dots, a_n, where n≥1n \geq 1, ana_n is at the top of the stack, and a0a_0 is at the bottom. The following algorithm computes f(x)=∑i=0naixif(x) = \sum_{i=0}^n a_i x^i. Identify the missing expression □\square in the pseudocode.
POLY(S,x)
1   while S.size > 1
2       u = S.pop()
3       v = S.pop()
4       S.push(□)
5   return S.pop()

(A) v⋅x+uv \cdot x + u
(B) u⋅x+vu \cdot x + v
(C) v⋅u+xv \cdot u + x
(D) u⋅v+xu \cdot v + x
(E) None of the other choices.

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

這一題的完整詳解

核心觀念

本題結合「堆疊(Stack)資料結構」與「多項式求值的霍納法則(Horner's Method)」。

  1. 堆疊(Stack)的後進先出(LIFO)特性:
    依題意,堆疊 SS 由頂端至底端依序為 an,an−1,…,a0a_n, a_{n-1}, \dots, a_0。因此在迴圈中,第一次執行 pop() 會取出位於最頂端的最高次項係數 ana_n,第二次 pop() 則取出次高次項係數 an−1a_{n-1}。
  2. 霍納法則(Horner's Method):
    對於 nn 次多項式 f(x)=∑i=0naixi=anxn+an−1xn−1+⋯+a1x+a0f(x) = \sum_{i=0}^n a_i x^i = a_n x^n + a_{n-1} x^{n-1} + \dots + a_1 x + a_0,霍納法則將其改寫為嵌套乘法形式:
    f(x)=(…((an⋅x+an−1)⋅x+an−2)⋅x+⋯+a1)⋅x+a0f(x) = (\dots((a_n \cdot x + a_{n-1}) \cdot x + a_{n-2}) \cdot x + \dots + a_1) \cdot x + a_0
    這種計算方式只需 nn 次乘法與 nn 次加法,是多項式求值最有效率的演算法。

解題方法

透過追蹤演算法在迴圈中的堆疊彈出(pop)與壓入(push)過程,可推導出空格 □\square 應填入的運算式。

1. 初始狀態與變數賦值
堆疊內部內容由頂端至底端為:
Stack S=[an,an−1,an−2,…,a0](Top → Bottom)\text{Stack } S = [a_n, a_{n-1}, a_{n-2}, \dots, a_0] \quad (\text{Top } \rightarrow \text{ Bottom})

2. 第一輪迴圈(Iteration 1)

  • 執行第 2 行 u = S.pop():取出頂端元素,此時 u=anu = a_n。
  • 執行第 3 行 v = S.pop():取出次頂端元素,此時 v=an−1v = a_{n-1}。
  • 根據霍納法則,第一階段需計算出 an⋅x+an−1a_n \cdot x + a_{n-1}。
  • 將 u=anu = a_n 與 v=an−1v = a_{n-1} 代入,該計算式即為:
    u⋅x+vu \cdot x + v
  • 執行第 4 行 S.push(u * x + v) 後,堆疊頂端變為 (anx+an−1)(a_n x + a_{n-1})。

3. 第二輪迴圈(Iteration 2)

  • 執行第 2 行 u = S.pop():此時 u=anx+an−1u = a_n x + a_{n-1}。
  • 執行第 3 行 v = S.pop():此時 v=an−2v = a_{n-2}。
🔒

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

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

免費註冊

第 2 題4 分

  1. (4 points) For positive functions f(n)f(n) and g(n)g(n) on N. If f(n)=O(g(n))f(n) = O(g(n)) and f(n)=Ω(1)f(n) = \Omega(1), how many of the following statements are true?
    • g(n)=Ω(f(n))g(n) = \Omega(f(n))
    • f(n)⋅log⁡(1+f(n))=O(g(n)⋅log⁡(1+g(n)))f(n) \cdot \log(1+f(n)) = O(g(n) \cdot \log(1+g(n)))
    • g(n)=O(2f(n))g(n) = O(2^{f(n)})
    • f(n)k=O(g(n)k)f(n)^k = O(g(n)^k) for any 0<k<10 < k < 1

(A) 0
(B) 1
(C) 2
(D) 3
(E) 4

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

這一題的完整詳解

核心觀念

本題旨在考驗**漸近記號(Asymptotic Notation)**的嚴格數學定義及其代數運算性質。主要涵蓋以下關鍵觀念:

  1. OO 記號與 Ω\Omega 記號的雙重性(Duality):對正函數而言,f(n)=O(g(n))  ⟺  g(n)=Ω(f(n))f(n) = O(g(n)) \iff g(n) = \Omega(f(n))。
  2. 正函數與常數下界:條件 f(n)=Ω(1)f(n) = \Omega(1) 代表存在常數 c0>0c_0 > 0,使得對足夠大的 nn,恆有 f(n)≥c0f(n) \ge c_0。此條件確保對數與冪次運算時不會產生趨近於零或未定義的極限異常。
  3. 單調函數對漸近比較的保序性:分析 f(n)=O(g(n))f(n) = O(g(n)) 在經過對數、冪次與指數函數作用後,其漸近等級是否仍被保持。

解題方法

本題包含四個獨立的命題判定,切入點如下:

  1. 定義法(直接推導):針對第一項與第四項敘述,直接利用 OO 記號的數學定義(常數倍不等式)進行同方向的移項與次冪縮放。
  2. 不等式放縮法:針對第二項敘述,結合 f(n)=Ω(1)f(n) = \Omega(1) 提供的不等式下界,利用對數函數在正數區間的對數放縮性質進行比較。
  3. 反例排除法(Counterexample):針對第三項敘述,考慮 f(n)=O(g(n))f(n) = O(g(n)) 只限定了 g(n)g(n) 的增長下界而非上界,構造超指數增長函數來反駁。

選項分析

  • 敘述一:g(n)=Ω(f(n))g(n) = \Omega(f(n)) — 【正確】

    • 證明:依據 f(n)=O(g(n))f(n) = O(g(n)) 的定義,存在正實數常數 c1>0c_1 > 0 與正整數 n0n_0,使得對所有 n≥n0n \ge n_0,恆有:
      f(n)≤c1⋅g(n)f(n) \le c_1 \cdot g(n)
    • 由於 c1>0c_1 > 0,將不等式兩邊同除以 c1c_1,可得:
      g(n)≥(1c1)⋅f(n)g(n) \ge \left(\frac{1}{c_1}\right) \cdot f(n)
    • 取常數 c2=1c1>0c_2 = \frac{1}{c_1} > 0,即符合 Ω\Omega 記號之定義:存在常數 c2>0c_2 > 0,對所有 n≥n0n \ge n_0 均有 g(n)≥c2⋅f(n)g(n) \ge c_2 \cdot f(n),故 g(n)=Ω(f(n))g(n) = \Omega(f(n)) 成立。
  • 敘述二:f(n)⋅log⁡(1+f(n))=O(g(n)⋅log⁡(1+g(n)))f(n) \cdot \log(1+f(n)) = O(g(n) \cdot \log(1+g(n))) — 【正確】

    • 證明:由已知條件,存在 c1>0c_1 > 0 與 c0>0c_0 > 0,使得當 n≥n0n \ge n_0 時,c0≤f(n)≤c1⋅g(n)c_0 \le f(n) \le c_1 \cdot g(n)。
    • 由於 g(n)≥1c1f(n)≥c0c1>0g(n) \ge \frac{1}{c_1} f(n) \ge \frac{c_0}{c_1} > 0,設 a=c0c1>0a = \frac{c_0}{c_1} > 0,故 g(n)g(n) 亦具備正常數下界。
    • 考慮對數部分的縮放:
      • 若 c1≤1c_1 \le 1,則 f(n)≤g(n)f(n) \le g(n)。由於 h(x)=log⁡(1+x)h(x) = \log(1+x) 在 x>0x > 0 為嚴格單調遞增函數,故 log⁡(1+f(n))≤log⁡(1+g(n))\log(1+f(n)) \le \log(1+g(n)) 直接成立。
      • 若 c1>1c_1 > 1,則:
        log⁡(1+f(n))≤log⁡(1+c1g(n))=log⁡(c1(1c1+g(n)))<log⁡(c1(1+g(n)))=log⁡c1+log⁡(1+g(n))\log(1+f(n)) \le \log(1+c_1 g(n)) = \log\left(c_1\left(\frac{1}{c_1} + g(n)\right)\right) < \log(c_1(1+g(n))) = \log c_1 + \log(1+g(n))
      • 因 g(n)≥a>0g(n) \ge a > 0,可知 log⁡(1+g(n))≥log⁡(1+a)>0\log(1+g(n)) \ge \log(1+a) > 0。因此:
🔒

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

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

免費註冊

第 3 題4 分

  1. (4 points) In 2022, DeepMind's AlphaTensor discovered a new state-of-the-art strategy for multiplying two N×NN \times N matrices using only 47 multiplications (under a special arithmetic) instead of the original 49. By integrating this method into a standard divide-and-conquer framework, the complexity for multiplying two N×NN \times N matrices is reduced to O(Nx)O(N^x). Compute xx based on the above information to get the tightest upper bound.

(A) log⁡247\log_2 47
(B) log⁡4(47+49)\log_4 (47 + 49)
(C) log⁡247\log_2 47
(D) log⁡10(47+49)\log_{10} (47 + 49)
(E) log⁡1047\log_{10} 47

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

這一題的完整詳解

核心觀念

本題考驗分治法(Divide-and-Conquer)矩陣乘法的時間複雜度分析,以及**主定理(Master Theorem)**的應用。

  1. 矩陣乘法分治法:
    將邊長為 NN 的矩陣切分為邊長為 Nb\frac{N}{b} 的子矩陣,若完成一次大矩陣乘法需要 aa 次子矩陣乘法,則時間複雜度遞迴式為:
    T(N)=aT(Nb)+O(N2)T(N) = a T\left(\frac{N}{b}\right) + O(N^2)
  2. 主定理(Master Theorem):
    對於遞迴式 T(N)=aT(Nb)+O(Nd)T(N) = a T\left(\frac{N}{b}\right) + O(N^d):
    • 若 a>bda > b^d(即 log⁡ba>d\log_b a > d),則時間複雜度為 O(Nlog⁡ba)O\left(N^{\log_b a}\right),指數 x=log⁡bax = \log_b a。

解題方法

  1. 確定分割基底與子問題數量:

    • 傳統 Strassen 演算法是將 N×NN \times N 矩陣視為 2×22 \times 2 個大小為 N2×N2\frac{N}{2} \times \frac{N}{2} 的子矩陣,使用 7 次乘法。若連續遞迴應用兩層於 4×44 \times 4 結構,乘法次數為 7×7=497 \times 7 = 49 次。
    • DeepMind 的 AlphaTensor 演算法針對 4×44 \times 4 矩陣結構進行優化,將 N×NN \times N 矩陣分割為 4×44 \times 4 個大小為 N4×N4\frac{N}{4} \times \frac{N}{4} 的子矩陣(故分割基底 b=4b = 4),且僅需 47 次子矩陣乘法(故子問題數量 a=47a = 47)。
  2. 建立遞迴關係式:
    T(N)=47T(N4)+O(N2)T(N) = 47 T\left(\frac{N}{4}\right) + O(N^2)

🔒

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

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

免費註冊

第 4 題4 分

  1. (4 points) Which of the following generates a uniformly random permutation of an array AA of size nn in place, assuming that RANDOM(ℓ,r\ell, r) returns an integer chosen uniformly at random from {ℓ,ℓ+1,…,r−1,r}\{\ell, \ell+1, \dots, r-1, r\}?
RANDOM-PERMUTE(A)
1   for i = 1 to n
2       j = □
3       if a ≥ b
4           swap A[i] with A[RANDOM(a,b)]

(A) a=RANDOM(1,n)a = \text{RANDOM}(1,n), b=RANDOM(a,n)b = \text{RANDOM}(a,n)
(B) a=ia = i, b=i−1b = i - 1
(C) a=ia = i, b=nb = n
(D) a=i+1a = i + 1, b=nb = n
(E) a=1a = 1, b=nb = n

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

這一題的完整詳解

核心觀念

  1. 均勻隨機排列(Uniformly Random Permutation)與 Fisher-Yates 洗牌演算法:

    • 長度為 nn 的陣列 AA 共有 n!n! 種不同的排列方式。若一個隨機化演算法能生成「均勻隨機排列」,則每一種排列產生的機率必須精確等於 1n!\frac{1}{n!}。
    • 根據經典的 Fisher-Yates 隨機洗牌演算法(即《Introduction to Algorithms》CLRS 中的 RANDOMIZE-IN-PLACE),在第 ii 輪迴圈迭代時(i=1,2,…,ni = 1, 2, \dots, n),必須將位於位置 ii 的元素與從剩餘未確定區間 {i,i+1,…,n}\{i, i+1, \dots, n\} 中均勻隨機選出的元素進行交換。
  2. 迴圈不變性(Loop Invariant):

    • 不變性條件:在第 ii 輪迴圈執行前,子陣列 A[1…i−1]A[1 \dots i-1] 包含從原本 nn 個元素中均勻選出的 i−1i-1 個元素之任意排列,且每一種可能的 (i−1)(i-1)-排列出現機率均為 (n−(i−1))!n!=(n−i+1)!n!\frac{(n - (i - 1))!}{n!} = \frac{(n-i+1)!}{n!}。
    • 終止條件:當迴圈結束(i=n+1i = n + 1)時,子陣列 A[1…n]A[1 \dots n] 即形成完整的均勻隨機排列,其出現機率為 1n!\frac{1}{n!}。

解題方法

為了確保演算法產生的每種排列機率皆為 1n!\frac{1}{n!},必須保證在第 ii 步時,從包含位置 ii 及其後續共 n−i+1n - i + 1 個候選位置中,以相等的機率 1n−i+1\frac{1}{n - i + 1} 隨機選擇一個索引與 A[i]A[i] 交換。

  1. 關鍵推導與機率計算:
    • 第 i=1i = 1 步:從 A[1…n]A[1 \dots n] 的 nn 個位置中隨機選擇一個放入 A[1]A[1],選擇機率為 1n\frac{1}{n}。
    • 第 i=2i = 2 步:從 A[2…n]A[2 \dots n] 的 n−1n-1 個位置中隨機選擇一個放入 A[2]A[2],選擇機率為 1n−1\frac{1}{n-1}。
    • 第 ii 步:從 A[i…n]A[i \dots n] 的 n−i+1n - i + 1 個位置中隨機選擇一個放入 A[i]A[i],選擇機率為 1n−i+1\frac{1}{n - i + 1}。
    • 生成任何特定排列的總機率為各步選擇機率之連乘積:
      P=1n×1n−1×1n−2×⋯×11=1n!P = \frac{1}{n} \times \frac{1}{n-1} \times \frac{1}{n-2} \times \dots \times \frac{1}{1} = \frac{1}{n!}
    • 由此可明確導出:隨機抽樣區間的下界必須為 a=ia = i,上界必須為 b=nb = n。
🔒

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

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

免費註冊

第 5 題4 分

  1. (4 points) Which of the following statements is known to be true?
    • Every NP-hard problem is polynomial-time reducible to every problem in NP.
    • Every NP-complete problem is polynomial-time reducible to every problem in NP.
    • Every problem solvable in polynomial time is polynomial-time reducible to every problem in NP.
    • Every problem solvable in exponential time is polynomial-time reducible to every problem in NP.
      (E) None of the other choices.

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

這一題的完整詳解

核心觀念

本題考驗計算複雜度理論(Computational Complexity Theory)中**多項式時間歸約(Polynomial-time Reduction)**的嚴格定義,以及複雜度類別 P\text{P}、NP\text{NP}、NP-complete\text{NP-complete} 與 NP-hard\text{NP-hard} 的性質。

  1. 多項式時間多一歸約(Polynomial-time Many-one Reduction / Karp Reduction)定義:
    語言(問題)AA 可在多項式時間內歸約至語言 BB(記為 A≤PBA \le_P B),當且僅當存在一個可在多項式時間內計算的函數 f:Σ∗→Σ∗f: \Sigma^* \to \Sigma^*,使得對所有輸入字串 xx,下列條件恆成立:
    x∈A  ⟺  f(x)∈Bx \in A \iff f(x) \in B
    這意味著 BB 的難度「至少與 AA 一樣高」(或 AA 的難度不大於 BB)。

  2. 極端語言(Trivial Languages):

    • 空集合 ∅\emptyset 與全集合 Σ∗\Sigma^* 皆屬於 P⊆NP\text{P} \subseteq \text{NP}(可在 O(1)O(1) 時間內判定)。
    • 對於任何非空且非全集(即非平凡,Non-trivial)的語言 AA:
      • 若歸約至 B=∅B = \emptyset,則對任意 x∈Ax \in A,f(x)∈∅f(x) \in \emptyset 永遠為假,無法滿足 x∈A  ⟺  f(x)∈Bx \in A \iff f(x) \in B。
      • 若歸約至 B=Σ∗B = \Sigma^*,則對任意 x∉Ax \notin A,f(x)∈Σ∗f(x) \in \Sigma^* 永遠為真,亦無法滿足 x∈A  ⟺  f(x)∈Bx \in A \iff f(x) \in B。
    • 結論:任何非平凡語言都無法多項式時間歸約至 ∅\emptyset 或 Σ∗\Sigma^*。

解題方法

要判斷一個敘述「Every problem in class C\mathcal{C} is polynomial-time reducible to every problem in NP\text{NP}」是否已知為真,必須驗證是否對 NP\text{NP} 中的每一個問題 BB(包含極端問題 ∅\emptyset 與 Σ∗\Sigma^*)都能找到對應的歸約函數。

  1. 反例檢驗法(極端語言):
    因為 ∅∈NP\emptyset \in \text{NP} 且 Σ∗∈NP\Sigma^* \in \text{NP},若選項所述的語言集合包含任何非平凡問題,該問題便無法歸約至 ∅\emptyset 或 Σ∗\Sigma^*,導致敘述不成立。

  2. 複雜度難易度邏輯:
    若問題 AA 比問題 BB 更難(例如 A∉PA \notin \text{P} 而 B∈PB \in \text{P}),除非 P=NP\text{P} = \text{NP},否則不可能存在 A≤PBA \le_P B。目前已知科學界並未證明 P=NP\text{P} = \text{NP},因此不能假設此類歸約恆成立。

綜合以上兩點推導,選項 (A)、(B)、(C)、(D) 皆存在明確反例或依賴未證實之假設,故均非已知為真。


🔒

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

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

免費註冊

第 6 題4 分

  1. (4 points) How many of the statements below are known to be true?
    • Every problem in NP is polynomial-time reducible to some NP-hard problem.
    • Every problem in NP is polynomial-time reducible to some NP-complete problem.
    • Every problem in NP is polynomial-time reducible to some problem solvable within polynomial time.
    • Every problem in NP is polynomial-time reducible to some problem solvable within exponential time.

(A) 0
(B) 1
(C) 2
(D) 3
(E) 4

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

這一題的完整詳解

核心觀念

本題考驗計算複雜度理論(Computational Complexity Theory)中關於**多項式時間規約(Polynomial-time Reduction, ≤P\le_P)**以及複雜度類別 P\text{P}、NP\text{NP}、NP-Hard\text{NP-Hard}、NP-Complete\text{NP-Complete} 與 EXPTIME\text{EXPTIME} 的基本定義與定理性質。

關鍵定義與性質

  1. 多項式時間規約(A≤PBA \le_P B):若問題 AA 可在多項式時間內規約至問題 BB,代表存在一個多項式時間可計算的函數 ff,使得對所有輸入 xx,x∈A  ⟺  f(x)∈Bx \in A \iff f(x) \in B。規約表示「問題 AA 的難度不超過問題 BB」;若 BB 可在某時間複雜度內解決,則 AA 亦可在該複雜度加上規約時間後解決。
  2. NP\text{NP} 類別:可在非確定性多項式時間(Nondeterministic Polynomial Time)內解決的判定問題集合。
  3. NP-Hard\text{NP-Hard} 類別:若一個問題 HH 滿足「對所有 L∈NPL \in \text{NP},皆有 L≤PHL \le_P H」,則稱 HH 為 NP-Hard\text{NP-Hard}。
  4. NP-Complete\text{NP-Complete} 類別:若問題 CC 同時滿足 (1) C∈NPC \in \text{NP} 且 (2) C∈NP-HardC \in \text{NP-Hard},則稱 CC 為 NP-Complete\text{NP-Complete}。
  5. 複雜度類別包含關係:
    P⊆NP⊆EXPTIME\text{P} \subseteq \text{NP} \subseteq \text{EXPTIME}
    其中 EXPTIME\text{EXPTIME} 為可在確定性指數時間(O(2nk)O(2^{n^k}))內解決的問題集合。

解題方法

針對題目中的四個敘述,依序運用計算複雜度理論的定理與定義檢驗其是否「已被證明為真(Known to be true)」:

  1. 檢驗敘述一與敘述二:根據 Cook-Levin 定理,已知存在 NP-Complete\text{NP-Complete} 問題(例如 SAT、3-SAT)。由 NP-Hard\text{NP-Hard} 與 NP-Complete\text{NP-Complete} 的定義即可判斷任何 NP\text{NP} 問題是否都能規約至這些問題。
  2. 檢驗敘述三:分析若所有 NP\text{NP} 問題皆可規約至 P\text{P} 類別問題時會導出何種結論,並判斷該結論是否為已知事實。
  3. 檢驗敘述四:利用包含關係 NP⊆EXPTIME\text{NP} \subseteq \text{EXPTIME} 以及恆等規約(Identity Reduction)來驗證其正確性。

最後統計已知為真的敘述數量並選出對應選項。


選項分析

敘述逐一分析

  • 敘述一:Every problem in NP is polynomial-time reducible to some NP-hard problem.

    • 分析:正確(Known to be true)。
    • 推導:根據 NP-Hard\text{NP-Hard} 的定義,問題 HH 為 NP-Hard\text{NP-Hard} 當且僅當對任意 L∈NPL \in \text{NP},均滿足 L≤PHL \le_P H。根據 Cook-Levin 定理,3-SAT 是一個 NP-Complete\text{NP-Complete} 問題,因此 3-SAT 必然屬於 NP-Hard\text{NP-Hard}。故對於任意 A∈NPA \in \text{NP},皆滿足 A≤P3-SATA \le_P \text{3-SAT}。因此,所有 NP\text{NP} 問題都能多項式時間規約至某個 NP-Hard\text{NP-Hard} 問題(例如 3-SAT),此敘述已知為真。
  • 敘述二:Every problem in NP is polynomial-time reducible to some NP-complete problem.

    • 分析:正確(Known to be true)。
🔒

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

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

免費註冊

第 7 題4 分

  1. (4 points) A company needs to assign 3 workers to 3 tasks. Each worker can perform only the tasks listed below:
    • Worker W1: Tasks T1, T2
    • Worker W2: Task T1
    • Worker W3: Tasks T3, T3
      Each worker can be assigned to at most one task, and each task to at most one worker. Which of the following statements is true?

(A) The maximum matching has size 2.
(B) The maximum matching has size 1.
(C) No matching exists.
(D) There are exactly two distinct maximum matchings.
(E) There exists a perfect matching.

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

這一題的完整詳解

核心觀念

本題考查圖論(Graph Theory)中的二分圖匹配(Bipartite Matching)與完美匹配(Perfect Matching)。

  • 二分圖(Bipartite Graph):頂點集可劃分為兩個互斥的集合 WW(工人集合)與 TT(工作集合),且圖中的每一條邊皆跨越兩集合(即一端點屬於 WW,另一端點屬於 TT)。
  • 匹配(Matching):邊集的子集 MM,滿足 MM 中任意兩條邊都沒有共同的頂點(即每位工人至多分配給一項工作,每項工作至多分配給一位工人)。
  • 最大匹配(Maximum Matching):包含邊數最多的匹配,其邊數稱為最大匹配大小(Size of Maximum Matching)。
  • 完全匹配/完美匹配(Perfect Matching):當二分圖兩側頂點數相等(∣W∣=∣T∣=n|W| = |T| = n),且存在一個大小為 nn 的匹配(即所有頂點均成功配對)時,該匹配即為完美匹配。

解題方法

  1. 建立二分圖模型:

    • 工人集合 W={W1,W2,W3}W = \{W_1, W_2, W_3\}
    • 工作集合 T={T1,T2,T3}T = \{T_1, T_2, T_3\}
    • 可執行工作的相連邊為:
      • 工人 W1W_1 可執行:T1,T2  ⟹  T_1, T_2 \implies 邊為 (W1,T1),(W1,T2)(W_1, T_1), (W_1, T_2)
      • 工人 W2W_2 可執行:T1  ⟹  T_1 \implies 邊為 (W2,T1)(W_2, T_1)
      • 工人 W3W_3 可執行:T3  ⟹  T_3 \implies 邊為 (W3,T3)(W_3, T_3)
  2. 推導最大匹配:

    • 觀察度數(Degree)限制:
      • 工人 W3W_3 只有單一選擇 T3T_3,故若要匹配 W3W_3,必須選擇 (W3,T3)(W_3, T_3)。
      • 工人 W2W_2 只有單一選擇 T1T_1,故若要匹配 W2W_2,必須選擇 (W2,T1)(W_2, T_1)。
    • 分配工人 W1W_1:
      • 工作 T1T_1 已被 W2W_2 佔用,因此 W1W_1 僅剩工作 T2T_2 可選,即選擇 (W1,T2)(W_1, T_2)。
    • 組合出匹配集合:
🔒

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

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

免費註冊

第 8 題4 分

  1. (4 points) Given the string S=wwvwuvS = \text{wwvwuv}, compute the Knuth-Morris-Pratt function function π[0…7]\pi[0 \dots 7], where π[i]\pi[i] is the length of the longest proper prefix of S[0…i]S[0 \dots i] which is also a suffix of S[0…i]S[0 \dots i]. Which of the following is correct?

(A) π=[0,1,0,1,2,0,0]\pi = [0, 1, 0, 1, 2, 0, 0]
(B) π=[0,0,1,0,1,2,2,3]\pi = [0, 0, 1, 0, 1, 2, 2, 3]
(C) π=[0,0,1,2,3,4,1,2]\pi = [0, 0, 1, 2, 3, 4, 1, 2]
(D) π=[0,0,0,1,2,3,2,3]\pi = [0, 0, 0, 1, 2, 3, 2, 3]
(E) π=[0,0,1,1,2,2,2,3]\pi = [0, 0, 1, 1, 2, 2, 2, 3]

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

這一題的完整詳解

本題的核心考點為 Knuth-Morris-Pratt (KMP) 演算法 中的 前綴函數 (Prefix Function / Failure Function π\pi) 之計算。前綴函數 π[i]\pi[i] 定義為子字串 S[0…i]S[0 \dots i] 的**最長真前綴(Proper Prefix)同時也是真後綴(Proper Suffix)**的長度。掌握此觀念的關鍵在於理解:

  • 真前綴與真後綴:不可包含整個子字串本身(長度必須嚴格小於 i+1i+1)。
  • 轉移與回溯(Backtracking)機制:當字串比對失敗時,利用先前計算好的 π\pi 值快速跳轉,避免重複比對,達到線性時間複雜度。

完整解題過程與詳細推導

題目細節與印錯勘誤說明

若依題幹印出的字串 S=wwvwuvS = \text{wwvwuv}(長度為 6),其 0-based 前綴函數計算結果應為長度 6 的陣列 π[0…5]=[0,1,0,1,0,0]\pi[0 \dots 5] = [0, 1, 0, 1, 0, 0]。
然而觀察各選項:

  • 選項 (A) 包含 7 個元素:[0,1,0,1,2,0,0][0, 1, 0, 1, 2, 0, 0]
  • 其餘選項皆包含 8 個元素。

對照字串結構與選項 (A) 的數值可發現,原題目的完整字串應為長度為 7 的 S=wwvwwuvS = \text{wwvwwuv}(第 4 個字元為 w\text{w},題目漏印了一個 w\text{w}),其對應的前綴函數範圍為 π[0…6]\pi[0 \dots 6]。以下依據 KMP 前綴函數定義對 S=wwvwwuvS = \text{wwvwwuv} 進行逐字元詳細推導:

逐一計算 π[i]\pi[i]:

  1. i=0i = 0 (S[0…0]="w"S[0 \dots 0] = \text{"w"}):

    • 子字串長度為 1,其真前綴與真後綴皆僅有空字串 ε\varepsilon。
    • 因此 π[0]=0\pi[0] = 0。
  2. i=1i = 1 (S[0…1]="ww"S[0 \dots 1] = \text{"ww"}):

    • 真前綴集合:{"w"}\{\text{"w"}\}
    • 真後綴集合:{"w"}\{\text{"w"}\}
    • 最長相同前後綴為 "w"\text{"w"},長度為 1。
    • 因此 π[1]=1\pi[1] = 1。
  3. i=2i = 2 (S[0…2]="wwv"S[0 \dots 2] = \text{"wwv"}):

    • 真前綴集合:{"w","ww"}\{\text{"w"}, \text{"ww"}\}
    • 真後綴集合:{"v","wv"}\{\text{"v"}, \text{"wv"}\}
    • 無任何重疊交集,最長相同前後綴長度為 0。
    • 因此 π[2]=0\pi[2] = 0。
  4. i=3i = 3 (S[0…3]="wwvw"S[0 \dots 3] = \text{"wwvw"}):

    • 真前綴集合:{"w","ww","wwv"}\{\text{"w"}, \text{"ww"}, \text{"wwv"}\}
    • 真後綴集合:{"w","vw","wvw"}\{\text{"w"}, \text{"vw"}, \text{"wvw"}\}
    • 最長相同前後綴為 "w"\text{"w"},長度為 1。
    • 因此 π[3]=1\pi[3] = 1。
  5. i=4i = 4 (S[0…4]="wwvww"S[0 \dots 4] = \text{"wwvww"}):

    • 真前綴集合:{"w","ww","wwv","wwvw"}\{\text{"w"}, \text{"ww"}, \text{"wwv"}, \text{"wwvw"}\}
    • 真後綴集合:{"w","ww","vww","wvww"}\{\text{"w"}, \text{"ww"}, \text{"vww"}, \text{"wvww"}\}
🔒

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

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

免費註冊

第 9 題4 分

  1. (4 points) Which of the following is the root of unity WN=e2πi/NW_N = e^{2\pi i / N}, where NN is a power of 2, allows the Cooley-Tukey fast-Fourier transform algorithm to achieve its speedup in time complexity?
    (A) The Magnitude Property: ∣WN∣=1|W_N| = 1 for all kk.
    (B) The Symmetry Property: WNk+N/2=−WNkW_N^{k+N/2} = -W_N^k, allowing dividing the problem into even/odd sub-problems.
    (C) The Orthogonality Property: The sum of all roots ∑k=0N−1WNk=0\sum_{k=0}^{N-1} W_N^k = 0.
    (D) The Conjugate Property: WN−k=WNN−kW_N^{-k} = W_N^{N-k}.
    (E) The Groom Property: There are exactly NN unique roots WNkW_N^k across all kk.

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

這一題的完整詳解

核心觀念

本題考驗**離散傅立葉變換(Discrete Fourier Transform, DFT)**與 Cooley-Tukey 快速傅立葉變換演算法(Fast Fourier Transform, FFT) 的核心數學性質。

傳統 DFT 計算 NN 點多項式求值的時間複雜度為 O(N2)O(N^2)。Cooley-Tukey 演算法利用分治法(Divide-and-Conquer)將複雜度降低至 O(Nlog⁡N)O(N \log N),其關鍵在於 NN 次單位複數根(Roots of Unity) WN=e2πi/NW_N = e^{2\pi i / N} 所具備的折半性質(Halving Lemma)與對稱性質(Symmetry Property / Negation Lemma)。


解題方法

假設有一 N−1N-1 次多項式:
A(x)=∑j=0N−1ajxjA(x) = \sum_{j=0}^{N-1} a_j x^j

將 A(x)A(x) 依據係數下標的奇偶性拆分為偶數項多項式 Aeven(x)A_{\text{even}}(x) 與奇數項多項式 Aodd(x)A_{\text{odd}}(x):
A(x)=Aeven(x2)+x⋅Aodd(x2)A(x) = A_{\text{even}}(x^2) + x \cdot A_{\text{odd}}(x^2)
其中:
Aeven(y)=∑j=0N/2−1a2jyj,Aodd(y)=∑j=0N/2−1a2j+1yjA_{\text{even}}(y) = \sum_{j=0}^{N/2-1} a_{2j} y^j, \quad A_{\text{odd}}(y) = \sum_{j=0}^{N/2-1} a_{2j+1} y^j

當我們在 x=WNkx = W_N^k (其中 0≤k<N/20 \le k < N/2)評估多項式時,利用折半性質 WN2k=WN/2kW_N^{2k} = W_{N/2}^k 可得:
A(WNk)=Aeven(WN/2k)+WNk⋅Aodd(WN/2k)A(W_N^k) = A_{\text{even}}(W_{N/2}^k) + W_N^k \cdot A_{\text{odd}}(W_{N/2}^k)

而評估後半段 x=WNk+N/2x = W_N^{k + N/2} 時,利用對稱性質 WNk+N/2=−WNkW_N^{k + N/2} = -W_N^k 與 WN2(k+N/2)=WN2k+N=WN2k=WN/2kW_N^{2(k+N/2)} = W_N^{2k + N} = W_N^{2k} = W_{N/2}^k 可得:
A(WNk+N/2)=Aeven(WN/2k)−WNk⋅Aodd(WN/2k)A(W_N^{k + N/2}) = A_{\text{even}}(W_{N/2}^k) - W_N^k \cdot A_{\text{odd}}(W_{N/2}^k)

關鍵推導結論:

透過對稱性質 WNk+N/2=−WNkW_N^{k + N/2} = -W_N^k,只要計算出子問題 Aeven(WN/2k)A_{\text{even}}(W_{N/2}^k) 與 Aodd(WN/2k)A_{\text{odd}}(W_{N/2}^k),就能同時在 O(1)O(1) 時間內算出 A(WNk)A(W_N^k) 與

🔒

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

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

免費註冊

第 10 題4 分

  1. (4 points) Consider an array [0,4,5,10,3,2,8][0, 4, 5, 10, 3, 2, 8]. What does the array look like after BUILD-MAX-HEAP (bottom-up heapify) is performed, a process that converts the array into a max-heap by adjusting subtrees starting from the bottom non-leaf nodes and working up to the root?

(A) [10,8,5,4,3,2,0][10, 8, 5, 4, 3, 2, 0]
(B) [10,5,8,4,3,2,0][10, 5, 8, 4, 3, 2, 0]
(C) [1,2,4,5,3,10,8][1, 2, 4, 5, 3, 10, 8]
(D) [10,7,1,5,2,4][10, 7, 1, 5, 2, 4]
(E) None of the other choices.

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

這一題的完整詳解

在 0‑index 陣列 A=[0,4,5,10,3,2,8]A=[0,4,5,10,3,2,8],n=7n=7,BUILD‑MAX‑HEAP 從最後一個非葉節點 i=⌊n/2⌋−1=2i=\lfloor n/2\rfloor-1=2 開始向上呼叫 MAX‑HEAPIFY。

  1. i = 2

    • 左子 A[5]=2A[5]=2,右子 A[6]=8A[6]=8,最大為 88。
    • 交換 A[2]↔A[6]A[2]\leftrightarrow A[6] → [0,4,8,10,3,2,5][0,4,8,10,3,2,5]。
  2. i = 1

    • 左子 A[3]=10A[3]=10,右子 A[4]=3A[4]=3,最大為 1010。
🔒

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

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

免費註冊

第 11 題4 分

  1. (4 points) Which pivot selection strategy in Quicksort is usually the most effective at avoiding the O(n2)O(n^2) worst-case runtime across arbitrary input distributions?

(A) Always select the first element.
(B) Always select the maximum element.
(C) Select a random element.
(D) Select the maximum of the first and last elements.
(E) Pivot selection does not change the algorithm's execution time.

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

這一題的完整詳解

核心觀念

本題考查**快速排序(Quicksort)**的樞紐(Pivot)選擇策略及其對時間複雜度的影響。

  1. 分治法與遞迴樹結構:Quicksort 採用分治法(Divide and Conquer)。將大小為 nn 的問題分割為兩個子問題,其時間複雜度遞迴式為:
    T(n)=T(k)+T(n−1−k)+Θ(n)T(n) = T(k) + T(n - 1 - k) + \Theta(n)
    其中 kk 與 n−1−kn - 1 - k 為劃分(Partition)後兩個子陣列的長度(0≤k≤n−10 \le k \le n-1)。
  2. 最壞時間複雜度 O(n2)O(n^2):當樞紐選擇極度不平均(例如每次皆選到當前陣列的最大值或最小值,導致 k=0k = 0 或 k=n−1k = n-1)時,遞迴樹深度退化至 O(n)O(n),總比較次數為:
    ∑i=1n(i−1)=n(n−1)2=Θ(n2)\sum_{i=1}^{n} (i - 1) = \frac{n(n-1)}{2} = \Theta(n^2)
  3. 隨機化演算法(Randomized Quicksort):透過隨機選擇樞紐(Select a random element),使算法表現與輸入資料的初始排列順序解耦(Decoupled)。對於任意輸入分佈(Arbitrary Input Distributions),其**期望時間複雜度(Expected Time Complexity)**均保持為 O(nlog⁡n)O(n \log n),有效消除特定惡意輸入(Adversarial Input)引發 O(n2)O(n^2) 最壞情況的風險。

解題方法

Quicksort 的效能完全取決於劃分點的平衡度:

  • 理想劃分:若樞紐始終能將陣列大致對分(例如 k≈n/2k \approx n/2),遞迴樹深度為 O(log⁡n)O(\log n),時間複雜度為最佳與平均的 O(nlog⁡n)O(n \log n)。
  • 確定性樞紐策略的局限:任何固定的選擇規則(如固定選首項、尾項、或特定位置的極值)都是確定性演算法(Deterministic Algorithm)。對於確定性策略,必然存在某種特定的輸入排列(例如已排序或逆序陣列),使得每一次劃分都落在極端邊界(k=0k=0),從而觸發最壞時間複雜度 O(n2)O(n^2)。
  • 隨機化樞紐策略的優勢:在每次劃分前,隨機均勻選取一個元素作為樞紐。選中落在中間 50%50\% 範圍(即第 2525 百分位數與第 7575 百分位數之間)的樞紐之概率恆為 1/21/2。即便面對惡意設計的輸入資料,隨機數產生器確保了每次劃分極大概率能有效縮減問題規模。經推導證明,隨機化 Quicksort 的期望比較次數為:
    E[T(n)]=2nln⁡n+O(n)=Θ(nlog⁡n)E[T(n)] = 2n \ln n + O(n) = \Theta(n \log n)
🔒

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

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

免費註冊

第 12 題4 分

  1. (4 points) Bucket sort has an expected linear runtime, O(n)O(n), under which of the following fundamental conditions?

(A) The input values are uniformly distributed over the interval.
(B) The input array is already sorted.
(C) All elements are placed in a single bucket.
(D) The number of buckets is the same as the number of input elements.
(E) The number of buckets is smaller than the number of input elements.

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

這一題的完整詳解

核心觀念

桶排序(Bucket Sort) 是一種基於數值分佈假設的非比較型/分配型排序演算法。其基本運作原理如下:

  1. 將區間 [0,1)[0, 1) 平均劃分為 nn 個子區間(稱為「桶」, Buckets)。
  2. 將 nn 個輸入元素依據數值映射至對應的桶中。
  3. 對每一個桶內部的元素分別進行排序(通常採用 Insertion Sort)。
  4. 依序收集並串聯所有桶中的元素,完成排序。

Bucket Sort 能達到期望線性時間複雜度 O(n)O(n) 的核心統計前提為:輸入資料必須獨立且均勻分佈(Uniformly Distributed)於給定區間內。在此假設下,每個桶分得的元素數量期望值為 O(1)O(1),進而保證整體排序時間與元素數量 nn 成正比。


解題方法

推導與複雜度分析:

  1. 基本假設與變數設定:
    設輸入陣列長度為 nn,劃分出 kk 個桶子(標準演算法通常取 k=nk = n)。假設輸入資料均勻分佈於區間 [0,1)[0, 1)。

  2. 單一桶子內元素量的統計特性:
    任一元素落入第 ii 個桶子的機率為 p=1k=1np = \frac{1}{k} = \frac{1}{n}。
    設第 ii 個桶子內含有的元素個數為隨機變數 nin_i,則 nin_i 服從二項分佈 Binomial(n,p)\text{Binomial}(n, p)。
    其二次矩(Second Moment)期望值計算如下:
    E[ni2]=Var(ni)+(E[ni])2=np(1−p)+(np)2E[n_i^2] = \text{Var}(n_i) + (E[n_i])^2 = n p (1 - p) + (n p)^2
    將 p=1np = \frac{1}{n} 代入:
    E[ni2]=n⋅1n(1−1n)+(n⋅1n)2=1−1n+1=2−1nE[n_i^2] = n \cdot \frac{1}{n} \left(1 - \frac{1}{n}\right) + \left(n \cdot \frac{1}{n}\right)^2 = 1 - \frac{1}{n} + 1 = 2 - \frac{1}{n}

  3. 總執行時間期望值計算:
    Bucket Sort 的總執行時間包含三個部分:

    • 散列與配置元素至各桶:Θ(n)\Theta(n)
    • 對各桶執行 Insertion Sort(單一桶耗時 O(ni2)O(n_i^2)):∑i=0n−1O(ni2)\sum_{i=0}^{n-1} O(n_i^2)
    • 串聯所有桶內元素:Θ(n)\Theta(n)

    計算總時間 T(n)T(n) 的期望值:
    E[T(n)]=Θ(n)+∑i=0n−1O(E[ni2])E[T(n)] = \Theta(n) + \sum_{i=0}^{n-1} O(E[n_i^2])
    代入 E[ni2]=2−1n=O(1)E[n_i^2] = 2 - \frac{1}{n} = O(1):
    E[T(n)]=Θ(n)+∑i=0n−1O(1)=Θ(n)+O(n)=O(n)E[T(n)] = \Theta(n) + \sum_{i=0}^{n-1} O(1) = \Theta(n) + O(n) = O(n)

🔒

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

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

免費註冊

第 13 題4 分

  1. (4 points) Which algorithm guarantees finding the median (the n/2n/2-th order statistic) of an array of nn elements in O(n)O(n) worst-case time?

(A) Sorting the array and then picking the median.
(B) Quickselect using random pivots.
(C) Using a max-heap or min-heap to extract the median.
(D) The median-of-medians selection algorithm.
(E) None of the other choices.

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

這一題的完整詳解

核心觀念

  • 順序統計量(Order Statistics)與中位數(Median):在含有 nn 個元素的未排序陣列中,尋找第 kk 小元素(第 kk 階順序統計量)的過程稱為選擇問題(Selection Problem)。當 k=⌊n/2⌋k = \lfloor n/2 \rfloor 或 ⌈n/2⌉\lceil n/2 \rceil 時,即為中位數。
  • 最壞時間複雜度(Worst-case Time Complexity):題目重點在於「保證(guarantees)」與「最壞時間複雜度(worst-case time)」。
  • Median-of-Medians 演算法(BFPRT 演算法):由 Blum、Floyd、Pratt、Rivest 與 Tarjan 五位學者提出的確定性選擇演算法。透過將陣列劃分為若干個大小為 5 的小組,遞迴求出「中位數的中位數」作為 Pivot(基準值),從而確保每一次 Partition 都能排除固定比例的元素,將最壞時間複雜度嚴格控制在 O(n)O(n)。

解題方法

本題評量對各種尋找中位數/順序統計量演算法時間複雜度的掌握度。

  1. BFPRT(Median-of-Medians)演算法的遞迴式與證明:
    將 nn 個元素每 5 個分為一組,共有 ⌈n/5⌉\lceil n/5 \rceil 組:
    • 找出每組的中位數:耗時 O(n)O(n)。
    • 遞迴尋找這 ⌈n/5⌉\lceil n/5 \rceil 個中位數的中位數作為 Pivot xx:耗時 T(⌈n/5⌉)T(\lceil n/5 \rceil)。
    • 以 xx 進行 Partition:至少有約半數的組,其組內中位數大於等於 xx,而在這些組中又有至少 3 個元素大於等於 xx(組內中位數本身及比它大的 2 個元素)。因此,大於等於 xx 的元素數量至少為:
      3×(⌈12⌈n5⌉⌉−2)≥3n10−63 \times \left( \left\lceil \frac{1}{2} \left\lceil \frac{n}{5} \right\rceil \right\rceil - 2 \right) \ge \frac{3n}{10} - 6
    • 同理,小於等於 xx 的元素數量也至少為 3n10−6\frac{3n}{10} - 6。因此劃分後,較大一方的子陣列元素數量至多為 7n10+6\frac{7n}{10} + 6。
    • 整體時間複雜度遞迴式可寫為:
      T(n)≤T(⌈n5⌉)+T(7n10+6)+O(n)T(n) \le T\left(\left\lceil \frac{n}{5} \right\rceil\right) + T\left(\frac{7n}{10} + 6\right) + O(n)
    • 利用代入法(Substitution Method)假設 T(n)≤cnT(n) \le c n,可解得 T(n)=O(n)T(n) = O(n)。因此該演算法能確定保證最壞情況為 O(n)O(n)。

選項分析

  • (A) Sorting the array and then picking the median.(錯誤)
    基於比較的排序演算法(如 Quick Sort、Merge Sort、Heap Sort)在最壞情況下的時間複雜度下界為 Ω(nlog⁡n)\Omega(n \log n)。
🔒

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

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

免費註冊

第 14 題4 分

  1. (4 points) A queue QQ is implemented using two stacks SinS_{in} and SoutS_{out} as follows. If each Push or Pop with the stack has a cost of O(1)O(1), what is the amortized cost per operation, over a sequence of mm legal queue operations, starting from an empty state with the first operation being ENQUEUE?
ENQUEUE(Q,z)
1   Push(Q.S_in, z)

DEQUEUE(Q)
1   if Q.S_out is not empty
2       return Pop(Q.S_out)
3   else if Q.S_in is not empty
4       while Q.S_in is not empty
5           Push(Q.S_out, Pop(Q.S_in))
6       return Pop(Q.S_out)

(A) O(1)O(1)
(B) O(log⁡m)O(\log m)
(C) O(m)O(m)
(D) O(m2)O(m^2)
(E) None of the other choices.

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

這一題的完整詳解

核心觀念

本題考查的核心觀念為雙堆疊實作佇列(Queue via Two Stacks)以及均攤分析(Amortized Analysis)。

  1. 資料結構特性:

    • 堆疊(Stack)遵從後進先出(LIFO, Last-In-First-Out)原則,Push 與 Pop 操作之時間複雜度均為 O(1)O(1)。
    • 佇列(Queue)遵從先進先出(FIFO, First-In-First-Out)原則。
    • 利用兩個堆疊 SinS_{in} 與 SoutS_{out},其中 SinS_{in} 負責接收新進元素(ENQUEUE),SoutS_{out} 負責輸出元素(DEQUEUE)。當 SoutS_{out} 為空且執行 DEQUEUE 時,將 SinS_{in} 中的所有元素依序 Pop 並 Push 至 SoutS_{out},可將 LIFO 順序翻轉為 FIFO 順序。
  2. 均攤分析(Amortized Analysis):

    • 用於評估一連串操作(Sequence of Operations)中,平均每次操作所花費的時間上限。即使個別操作在最壞情況下耗時較長,若發生頻率極低,整體平均成本仍可維持在較低的常數階層。
    • 主要分析方法包含:聚合分析法(Aggregate Method)與位能法(Potential Method)。

解題方法

此題可分別透過聚合分析法與位能法進行精確推導。

方法一:聚合分析法(Aggregate Analysis)

考慮由 mm 個合法佇列操作組成的序列,初始狀態佇列為空。

  1. 單一元素的生命週期分析:
    對於任意一個加入佇列的元素 zz,在整個操作序列中,最多只會經歷以下 4 次堆疊操作:

    • ENQUEUE 時:Push 入 SinS_{in}(1 次 Push)。
    • 轉移至 SoutS_{out} 時:從 SinS_{in} Pop 出(1 次 Pop),並 Push 入 SoutS_{out}(1 次 Push)。
    • DEQUEUE 時:從 SoutS_{out} Pop 出(1 次 Pop)。
  2. 總成本計算:
    在 mm 次佇列操作中,最多只能 ENQUEUE mm 個元素。因此,所有元素在整個生命週期中所產生的堆疊操作總次數上限為:
    4×m=4m4 \times m = 4m
    除堆疊操作外,每次 ENQUEUE 與 DEQUEUE 的條件判斷與控制流程時間均為 O(1)O(1)。因此 mm 次佇列操作的總花費時間上限為 O(m)O(m)。

  3. 均攤成本:
    每次操作的平均(均攤)成本為:
    Amortized Cost=Total Costm=O(m)m=O(1)\text{Amortized Cost} = \frac{\text{Total Cost}}{m} = \frac{O(m)}{m} = O(1)


方法二:位能法(Potential Method)

定義位能函數 Φ(D)=2⋅∣Sin∣\Phi(D) = 2 \cdot |S_{in}|,其中 ∣Sin∣|S_{in}| 表示堆疊 SinS_{in} 中的元素個數。

  • 初始狀態:D0D_0 為空佇列,Φ(D0)=0\Phi(D_0) = 0。
  • 合法性:對任意狀態 DiD_i,由於 ∣Sin∣≥0|S_{in}| \ge 0,故 Φ(Di)≥Φ(D0)=0\Phi(D_i) \ge \Phi(D_0) = 0 恆成立。

對第 ii 次佇列操作計算真實成本 cic_i 與均攤成本 c^i=ci+Φ(Di)−Φ(Di−1)\hat{c}_i = c_i + \Phi(D_i) - \Phi(D_{i-1}):

🔒

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

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

免費註冊

第 15 題4 分

  1. (4 points) Most hash table implementations (such as Java's HashMap) resize the underlying array when the load factor α\alpha exceeds a certain threshold (typically 0.75). Why is this resizing operation necessary for a hash table that uses separate chaining?

(A) Saturation: To prevent the table from reaching a load factor of 1.0, at which point inserting a new element would be impossible.
(B) Ordering: To re-sort the keys alphabetically during the transfer, enabling the use of binary search for future lookups.
(C) Complexity: To prevent the average length of the linked lists (collision chains) from growing linearly with the number of elements, thereby maintaining O(1)O(1) average access time.
(D) Uniformity: To redistribute the keys across a larger range so that all existing collisions are permanently eliminated.
(E) Memory contiguity: To ensure that all elements in the linked lists are stored in adjacent memory addresses, minimizing CPU cache misses and memory fragmentation.

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

這一題的完整詳解

在使用separate chaining的雜湊表,所有元素均放在長度為 mm 的陣列的桶中,每個桶含一條鏈表。
當加入 nn 個鍵後,負載係數 α=nm\alpha = \frac{n}{m},平均鏈長即為 α\alpha。若 α\alpha 持續增大,鏈表長度將與 nn 成線性關係,導致搜尋、插入、刪除的期望時間從 O(1)O(1) 退化為 O(α)=O(n)O(\alpha)=O(n).

🔒

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

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

免費註冊

第 16 題4 分

  1. (4 points) Assume that there are mm hash table keys 1,2,…,m1, 2, \dots, m and mm hash table slots 0,1,…,m−10, 1, \dots, m-1 with m>1m > 1. In double hashing, the probe sequence is
    h(k,i)=(h1(k)+i⋅h2(k))(modm)h(k, i) = (h_1(k) + i \cdot h_2(k)) \pmod m
    For a fixed key kk, we want the sequence h(k,0),h(k,1),…h(k, 0), h(k, 1), \dots to visit all mm table slots before repeating, so that insertion succeeds whenever the table is not full. Which of the following conditions is necessary and sufficient for this property (for that key kk)?

(A) mm must be prime.
(B) h1(k)h_1(k) must be odd.
(C) gcd⁡(h2(k),m)=1\gcd(h_2(k), m) = 1.
(D) gcd⁡(h1(k),m)=1\gcd(h_1(k), m) = 1 and h2(k)h_2(k) must be injective (one-to-one) from {1,2,…,K}\{1, 2, \dots, K\} to {0,1,…,m−1}\{0, 1, \dots, m-1\}.
(E) None of the other choices.

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

這一題的完整詳解

核心觀念

本題考查**雜湊表(Hash Table)採用開放定址法(Open Addressing)中的雙重雜湊(Double Hashing)**機制時,探測序列(Probe Sequence)能造訪所有槽位(Slots)的數學充要條件。

關鍵定義與定理:

  1. 雙重雜湊探測序列函數:
    h(k,i)=(h1(k)+i⋅h2(k))(modm),i=0,1,…,m−1h(k, i) = (h_1(k) + i \cdot h_2(k)) \pmod m, \quad i = 0, 1, \dots, m-1
    其中 h1(k)h_1(k) 為起始雜湊值(Initial Slot Offset),h2(k)h_2(k) 為探測步長(Step Size),mm 為雜湊表大小(Table Size)。
  2. 模同餘加法群的生成元定理(Group Generator in Zm\mathbb{Z}_m):
    在同餘加法群 (Zm,+)(\mathbb{Z}_m, +) 中,由步長 gg 所產生的序列 {(i⋅g)(modm)∣i≥0}\{ (i \cdot g) \pmod m \mid i \ge 0 \},其重複前的週期(Order / 子群階數)為:
    period=mgcd⁡(g,m)\text{period} = \frac{m}{\gcd(g, m)}
    若要使該序列包含 Zm\mathbb{Z}_m 中的所有 mm 個元素(即週期長度恰等於 mm),當且僅當步長 gg 與表長 mm 互質,即 gcd⁡(g,m)=1\gcd(g, m) = 1。

解題方法

對於一個給定的特定鍵值 kk,h1(k)h_1(k) 與 h2(k)h_2(k) 皆為確定之常數。

  1. 平移不影響探測週期長度:
    起始雜湊值 h1(k)(modm)h_1(k) \pmod m 僅代表探測序列在雜湊表中的起始平移位置。在 Zm\mathbb{Z}_m 中加上常數 h1(k)h_1(k) 屬於雙射映射(Bijection),探測序列 h(k,0),h(k,1),…,h(k,m−1)h(k, 0), h(k, 1), \dots, h(k, m-1) 能否覆蓋全部 mm 個槽位 {0,1,…,m−1}\{0, 1, \dots, m-1\},完全取決於步長序列 (i⋅h2(k))(modm)(i \cdot h_2(k)) \pmod m(i=0,1,…,m−1i = 0, 1, \dots, m-1)是否能遍歷 {0,1,…,m−1}\{0, 1, \dots, m-1\}。

  2. 探測序列週期的推導:
    以 h2(k)h_2(k) 為步長時,序列在重複前所產生的不同槽位個數為:
    Length=mgcd⁡(h2(k),m)\text{Length} = \frac{m}{\gcd(h_2(k), m)}

  3. 充要條件判定:
    題目要求探測序列在重複之前必須造訪所有 mm 個槽位,即週期長度必須等於 mm:
    mgcd⁡(h2(k),m)=m  ⟺  gcd⁡(h2(k),m)=1\frac{m}{\gcd(h_2(k), m)} = m \iff \gcd(h_2(k), m) = 1

🔒

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

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

免費註冊

第 17 題4 分

  1. (4 points) Consider the Binary Search Tree in Figure 1. If node 66 is removed (replacing it with its in-order successor), what is the resulting preorder traversal sequence?
    🖼️【此處有附圖,請對照原卷】
    Figure 1: Binary Search Tree

(A) 3, 23, 56, 57, 72.
(B) 56, 23, 3, 72, 67.
(C) 57, 23, 3, 72, 66.
(D) 56, 23, 3, 72, 3.
(E) None of the other choices.

🖼️ 本題含圖表,以下為原卷對應頁面:
原卷第 5 頁

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

這一題的完整詳解

1. 原始二元搜尋樹結構與中序走訪

根據圖 1,原始二元搜尋樹(Binary Search Tree, BST)的結構如下:

  • 根節點為 5656。
  • 5656 的左子節點為 2323,而 2323 的左子節點為 33。
  • 5656 的右子節點為 6666,而 6666 的左子節點為 5757、右子節點為 7272。

此樹的中序走訪(In-order Traversal)順序為:3,23,56,57,66,723, 23, 56, 57, 66, 72。


2. 刪除節點 6666

依題目要求,刪除節點 6666 並以其中序後繼者(In-order Successor)取代:

  1. 節點 6666 的中序後繼者為其右子樹中的最小節點,即 7272。
🔒

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

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

免費註冊

第 18 題4 分

  1. (4 points) Which of the following properties is true for some optimal prefix-free binary code and directly justifies the greedy choice made in the Huffman algorithm?

(A) The two symbols with the lowest frequencies must appear at the same depth in the code tree.
(B) The symbol with the lowest frequency must be assigned the longest codeword, but the symbol with the second smallest frequency need not.
(C) All leaves at the least depth must correspond to symbols with the lowest frequency.
(D) The two symbols with the lowest frequencies must have equal codeword lengths, but they need not share the same parent.
(E) The two symbols with the lowest frequencies must be siblings at the maximum depth of the code tree.

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

這一題的完整詳解

核心觀念

  • 赫夫曼編碼(Huffman Coding):一種用來建構最優前綴碼(Optimal Prefix-Free Binary Code)的貪婪演算法(Greedy Algorithm)。
  • 貪婪選擇性質(Greedy-Choice Property):演算法的每一步局部最佳選擇(將當前出現頻率最低的兩個符號合併)最終能導出全域最佳解(Global Optimum)。
  • 最優編碼樹(Code Tree)的結構性質:
    設 CC 為字元集,每位字元 c∈Cc \in C 的出現頻率為 f(c)f(c)。在編碼樹 TT 中,符號 cc 的深度記為 dT(c)d_T(c),即其編碼長度。編碼樹的總代價定義為平均編碼長度:
    B(T)=∑c∈Cf(c)⋅dT(c)B(T) = \sum_{c \in C} f(c) \cdot d_T(c)
    對於任意字元集,必然存在某一棵最優編碼樹 TT,滿足:出現頻率最低的兩個符號 x,y∈Cx, y \in C 位居樹的最大深度(Maximum Depth),且兩者互為兄弟節點(Siblings)(即共享相同的父節點,僅在最後一位元有所不同)。

解題方法

本題考查 Huffman 演算法正確性證明中的關鍵步驟——貪婪選擇性質引理(Greedy-Choice Property Lemma)。

推導與證明步驟(Exchange Argument 交換法)

  1. 假設基準樹:
    設 TT 為任意一棵最優前綴碼樹。設樹中深度最深且互為兄弟節點的兩個葉節點分別為 aa 與 bb(即 dT(a)=dT(b)d_T(a) = d_T(b) 為樹的最大深度)。
  2. 頻率比較:
    設 xx 與 yy 為整個字元集中頻率最低的兩個符號,滿足 f(x)≤f(y)f(x) \le f(y)。因為 x,yx, y 的頻率最低,故必有:
    f(x)≤f(a)且f(y)≤f(b)f(x) \le f(a) \quad \text{且} \quad f(y) \le f(b)
  3. 位置交換(Swap):
    • 若 xx 原本不在最深層節點 aa 的位置,我們將 xx 與 aa 在樹中的位置互換,得到新樹 T′T'。交換後代價變化量為:
      B(T)−B(T′)=f(a)⋅dT(a)+f(x)⋅dT(x)−(f(x)⋅dT(a)+f(a)⋅dT(x))=(f(a)−f(x))(dT(a)−dT(x))B(T) - B(T') = f(a) \cdot d_T(a) + f(x) \cdot d_T(x) - \bigl(f(x) \cdot d_T(a) + f(a) \cdot d_T(x)\bigr) = (f(a) - f(x))(d_T(a) - d_T(x))
🔒

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

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

免費註冊

第 19 題4 分

  1. (4 points) Consider a dynamic table (1) that starts empty with capacity 1; (2) doubles its capacity when full; (3) shrinks its capacity by a factor of 1/2 when the capacity ≥4\geq 4 and the number of stored elements falls below 1/4 of the capacity. Assume that inserting or deleting an element costs 1, and resizing a table of size kk costs Θ(k)\Theta(k). Which statement is true when considering nn insert and several operations?

(A) The worst-case cost of any single operation is O(1)O(1), so amortized analysis is unnecessary.
(B) Using aggregate analysis, the amortized cost per operation is Θ(log⁡n)\Theta(\log n).
(C) If shrinking were performed when the table becomes half full instead of one quarter full, but the amortized cost would still be O(1)O(1).
(D) With the one-quarter shrinking rule, the amortized cost per operation is O(1)O(1), but shrinking more aggressively will half capacity when the table is half-full can destroy this bound.
(E) The amortized cost depends on the order of operations and cannot be bounded independently of the operation sequence.

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

這一題的完整詳解

核心觀念

本題考查動態表格(Dynamic Table / Dynamic Array)的分攤分析(Amortized Analysis),特別是表格擴充(Expansion)與縮減(Contraction/Shrinking)的觸發機制及「抖動現象(Thrashing)」。

  1. 單次操作最差時間複雜度:當表格滿載或過度空置而觸發重構(Resize)時,複製 kk 個元素的成本為 Θ(k)\Theta(k),因此單次操作的最差時間複雜度為 Θ(k)\Theta(k)。
  2. 裝載因子(Load Factor α\alpha):定義為 α=nm\alpha = \frac{n}{m},其中 nn 為已儲存的元素數量,mm 為當前表格容量。
    • 擴充機制:當 α=1\alpha = 1 且執行 Insert 時,容量加倍(m→2mm \to 2m),複製成本為 Θ(m)\Theta(m)。
    • 1/41/4 縮減機制:當容量 m≥4m \geq 4 且 α<1/4\alpha < 1/4(即元素數跌破 m/4m/4)時,容量減半(m→m/2m \to m/2)。此機制確保重構完成後,裝載因子回復至 α=1/2\alpha = 1/2,留下足夠的「緩衝區(Buffer)」。
  3. 抖動現象(Thrashing):若將縮減條件設為 α<1/2\alpha < 1/2(半滿即減半),在元素數量於 m/2m/2 附近擺盪時,連續交替執行 Insert 與 Delete 會導致每次操作都觸發 Resize,使單次操作的分攤成本大幅退化至 Θ(m)\Theta(m)。

解題方法

1. 1/41/4 縮減規則下的分攤成本證明(勢能法 Potential Method)

定義勢能函數(Potential Function) Φ(T)\Phi(T):
Φ(T)={2n−mif α≥1/2m2−nif α<1/2\Phi(T) = \begin{cases} 2n - m & \text{if } \alpha \geq 1/2 \\ \frac{m}{2} - n & \text{if } \alpha < 1/2 \end{cases}

  • 勢能性質:

    1. 當 α=1/2\alpha = 1/2 時,Φ(T)=0\Phi(T) = 0。
    2. 當 α=1\alpha = 1 時(擴充前夕),Φ(T)=2m−m=m\Phi(T) = 2m - m = m,累積的勢能足以支付擴充所需複製 mm 個元素的成本。
    3. 當 α=1/4\alpha = 1/4 時(縮減前夕),Φ(T)=m2−m4=m4\Phi(T) = \frac{m}{2} - \frac{m}{4} = \frac{m}{4},累積的勢能足以支付縮減至 m/2m/2 時複製 m/4m/4 個元素的成本。
    4. 初始狀態(n=0,m=1n=0, m=1)Φ(T0)=0\Phi(T_0) = 0,且對所有狀態均有 Φ(T)≥0\Phi(T) \geq 0。
  • 分攤成本(Amortized Cost c^i=ci+Φ(Ti)−Φ(Ti−1)\hat{c}_i = c_i + \Phi(T_i) - \Phi(T_{i-1}))推導:

    • 一般插入/刪除(未觸發 Resize):實際成本 ci=1c_i = 1,勢能變化 ΔΦ≤2\Delta \Phi \leq 2,故分攤成本 c^i≤1+2=3=O(1)\hat{c}_i \leq 1 + 2 = 3 = O(1)。
    • 觸發擴充的插入(n=m+1n = m + 1):
      實際成本 ci=1+mc_i = 1 + m(包含複製 mm 個元素)。
      舊勢能 Φ(Ti−1)=2m−m=m\Phi(T_{i-1}) = 2m - m = m;新勢能 Φ(Ti)=2(m+1)−2m=2\Phi(T_i) = 2(m+1) - 2m = 2。
      分攤成本 c^i=(1+m)+(2−m)=3=O(1)\hat{c}_i = (1 + m) + (2 - m) = 3 = O(1)。
    • 觸發縮減的刪除(舊容量 mm,舊元素數 m4−1\frac{m}{4}-1):
🔒

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

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

免費註冊

第 20 題4 分

  1. (4 points) Consider a red-black tree augmented for dynamic order statistics by storing, at each node xx, the attribute x.size=number of nodes in the subtree rooted at xx.\text{size} = \text{number of nodes in the subtree rooted at } x, including xx itself. Which of the following statements is correct?

(A) During insertion, the size field needs to be updated only along the path from the root to the inserted node; rotations do not require any update to size.
(B) Because the size field needs to be updated, the size fields of exactly two nodes can be recomputed in O(1)O(1) time each during a left or right rotation, the size fields of exactly two nodes can be recomputed in O(1)O(1) time each.
(C) The SELECT(i) operation (finding the ii-th smallest key) requires O(log⁡n)O(\log n) extra space due to recursion.
(D) Maintaining the size field may violate the red-black tree properties and thus requires additional rebalancing rules.
(E) The presence of duplicate keys makes it impossible to support SELECT(i) correctly using subtree sizes.

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

這一題的完整詳解

解說

在每個節點 xx 保存 x.sizex.\text{size}(以 xx 為根之子樹節點數)時,對於紅黑樹的插入、旋轉以及 SELECT 操作的影響如下:

  1. 插入時的 size 更新
    插入新節點後,必須把從根到新節點的每條邊上的祖先節點的 size 加 1。旋轉會改變子樹結構,涉及的節點的 size 必須重新計算。因此旋轉不會免除 size 更新。 → (A) 錯。

  2. 旋轉時的 size 更新
    以左旋為例,旋轉前的節點 xx 與其右子 yy,旋轉後 yy 成為新的父節點,xx 成為 yy 的左子。

🔒

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

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

免費註冊

第 21 題4 分

  1. (4 points) Let PP be a B-tree of minimum degree t≥2t \geq 2. During the deletion of a key kk from an internal node xx, suppose xx has at least tt keys, which of the following actions correctly preserves all B-tree invariants before the recursive deletion process?

(A) Always replace kk with its inorder predecessor from the left subtree, regardless of the number of keys in the subtrees.
(B) Replace kk with either the predecessor or successor arbitrarily, since both choices always produce valid B-trees.
(C) Merge the two children of kk immediately, even if both have at least tt keys.
(D) Delete kk directly from node xx and rebalance only if an underflow occurs afterward.
(E) Replace kk with the key preceding kk in the left child if the left child has at least tt keys; otherwise, replace kk with the key following kk in the right child if the right child has at least tt keys.

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

這一題的完整詳解

核心觀念

  • B-樹(B-Tree)結構不變量(Invariants):
    • 設最小度數(minimum degree)為 t≥2t \geq 2。
    • 除根節點外,所有內部節點至少包含 t−1t-1 個鍵值(keys),至多包含 2t−12t-1 個鍵值。
    • 除根節點外,非葉內部節點的子樹數量 cc 與鍵值數 nn 滿足 c=n+1c = n + 1,且 t≤c≤2tt \leq c \leq 2t。
  • B-樹單向向下刪除機制(Top-Down Single-Pass Deletion):
    在經典 B-樹刪除演算法(CLRS 教科書規範)中,為了確保刪除操作可以在單次向下走訪過程中完成而無需向上回溯(backtracking),演算法會維護一個關鍵不變量:當訪問至某節點 xx 並欲刪除其中鍵值 kk 時,xx 及其下一個將被遞迴處理的目標節點均至少擁有 tt 個鍵值。
  • 從內部節點 xx 刪除鍵值 kk 的三大情況(Case 2):
    • Case 2a:若 kk 的左子節點 yy(前驅子節點)擁有至少 tt 個鍵值,則在以 yy 為根的子樹中找出 kk 的中序前驅鍵值(inorder predecessor)k′k',將 k′k' 填入 xx 替代 kk,並遞迴從 yy 的子樹中刪除 k′k'。
    • Case 2b:若 yy 的鍵值數僅有 t−1t-1 個,但右子節點 zz(後繼子節點)擁有至少 tt 個鍵值,則在以 zz 為根的子樹中找出 kk 的中序後繼鍵值(inorder successor)k′k',將 k′k' 填入 xx 替代 kk,並遞迴從 zz 的子樹中刪除 k′k'。
    • Case 2c:若 yy 與 zz 均只有 t−1t-1 個鍵值,則將 kk 與 zz 的所有鍵值併入 yy,使 yy 的鍵值數成為 (t−1)+1+(t−1)=2t−1(t-1) + 1 + (t-1) = 2t-1,釋放 zz,再遞迴從 yy 中刪除 kk。

解題方法

本題欲尋找在內部節點 xx(已滿足鍵值數 ≥t\geq t)中刪除鍵值 kk 時,於進入遞迴刪除前能正確維護所有 B-樹不變量的合法操作。

根據上述刪除機制:

  1. 若要從子樹中提取中序前驅或後繼鍵值來替換 kk,該子樹的根節點必須至少有 tt 個鍵值。否則從中刪除一個鍵值後,該子節點會剩餘 t−2t-2 個鍵值,直接引發下溢(underflow),違反 n≥t−1n \geq t-1 的限制。
🔒

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

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

免費註冊

第 22 題4 分

  1. (4 points) Let X=[x1,…,xm]X = [x_1, \dots, x_m] and Y=[y1,…,yn]Y = [y_1, \dots, y_n] be two sequences. Let L[i][j]L[i][j] denote the length of the longest common subsequence (LCS) of the prefixes X[1…i]X[1 \dots i] and Y[1…j]Y[1 \dots j], and let C[i][j]C[i][j] denote the number of distinct LCSs (distinct subsequences, not dynamic programming paths or alignments) of these prefixes. Let C[0][0]=1C[0][0]=1 since the empty sequence is a unique LCS. Which of the following recurrences correctly computes distinct LCSs?

(A)

If X[i] = Y[j]:
    C[i][j] = C[i-1][j-1]
Else:
    If L[i-1][j] > L[i][j-1]:
        C[i][j] = C[i-1][j]
    Else if L[i-1][j] < L[i][j-1]:
        C[i][j] = C[i][j-1]
    Else:
        C[i][j] = C[i-1][j] + C[i][j-1] - C[i-1][j-1]

(B)

If X[i] = Y[j]:
    C[i][j] = C[i-1][j-1]
Else:
    C[i][j] = C[i-1][j] + C[i][j-1] - C[i-1][j-1]

(C)

If X[i] = Y[j]:
    C[i][j] = C[i-1][j-1]
Else:
    C[i][j] = C[i-1][j] + C[i][j-1]

(D)

If X[i] = Y[j]:
    C[i][j] = 1
Else:
    C[i][j] = C[i-1][j] + C[i][j-1] - 1

(E)

If X[i] = Y[j]:
    C[i][j] = C[i-1][j-1]
Else:
    C[i][j] = C[i-1][j] + C[i][j-1] - C[i-1][j-1]

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

這一題的完整詳解

核心觀念

本題考查**最長公共子序列(Longest Common Subsequence, LCS)**在動態規劃(Dynamic Programming, DP)上的延伸應用——計算相異 LCS 的數量(Counting Distinct LCSs)。

給定兩序列 X=[x1,…,xm]X = [x_1, \dots, x_m] 與 Y=[y1,…,yn]Y = [y_1, \dots, y_n]:

  1. L[i][j]L[i][j] 的定義:前綴 X[1…i]X[1 \dots i] 與 Y[1…j]Y[1 \dots j] 的 LCS 長度。
  2. C[i][j]C[i][j] 的定義:前綴 X[1…i]X[1 \dots i] 與 Y[1…j]Y[1 \dots j] 之相異 LCS 的總個數(關注的是相異的子序列字串本身,而非 DP 表格上的路徑或對齊方式)。
  3. 邊界條件:
    • 空序列 ϵ\epsilon 的長度為 00,C[0][0]=1C[0][0] = 1(空序列本身是一條獨一無二長度為 00 的 LCS)。
    • 對於任意 i,ji, j,邊界 C[i][0]=1C[i][0] = 1 與 C[0][j]=1C[0][j] = 1。

在計算相異 LCS 數量時,核心在於利用 L[i][j]L[i][j] 的大小關係過濾出非最長的組合,並透過**排容原理(Inclusion-Exclusion Principle)**避免重複統計(Double Counting)。


解題方法

計算 C[i][j]C[i][j] 的轉移過程分為兩個主要狀況:

狀況一:當 X[i]=Y[j]X[i] = Y[j] 時

當前字元相同,則 X[i]X[i] 必定作為 X[1…i]X[1 \dots i] 與 Y[1…j]Y[1 \dots j] 之 LCS 的最後一個字元,且此時 LCS 長度增長 11(即 L[i][j]=L[i−1][j−1]+1L[i][j] = L[i-1][j-1] + 1)。

  • 任何 X[1…i]X[1 \dots i] 與 Y[1…j]Y[1 \dots j] 的 LCS 移除最後這個共同字元後,必然唯一對應到 X[1…i−1]X[1 \dots i-1] 與 Y[1…j−1]Y[1 \dots j-1] 的一條 LCS。
  • 因此,相異 LCS 的數量完全由 C[i−1][j−1]C[i-1][j-1] 決定:
    C[i][j]=C[i−1][j−1]C[i][j] = C[i-1][j-1]

狀況二:當 X[i]≠Y[j]X[i] \neq Y[j] 時

當前字元不同時,LCS 長度由兩個子問題決定:L[i][j]=max⁡(L[i−1][j],L[i][j−1])L[i][j] = \max(L[i-1][j], L[i][j-1])。相異 LCS 的來源需比較 L[i−1][j]L[i-1][j] 與 L[i][j−1]L[i][j-1] 的大小:

  1. 若 L[i−1][j]>L[i][j−1]L[i-1][j] > L[i][j-1]:
    長度達到最長(L[i][j]L[i][j])的 LCS 只能來自 X[1…i−1]X[1 \dots i-1] 與 Y[1…j]Y[1 \dots j]。由 X[1…i]X[1 \dots i] 與 Y[1…j−1]Y[1 \dots j-1] 產生的公共子序列長度較短,不可計入。
    C[i][j]=C[i−1][j]C[i][j] = C[i-1][j]

  2. 若 L[i−1][j]<L[i][j−1]L[i-1][j] < L[i][j-1]:
    同理,達到最大長度的 LCS 只能來自 X[1…i]X[1 \dots i] 與 Y[1…j−1]Y[1 \dots j-1]。
    C[i][j]=C[i][j−1]C[i][j] = C[i][j-1]

  3. 若 L[i−1][j]=L[i][j−1]L[i-1][j] = L[i][j-1]:
    兩邊都能提供長度為 L[i][j]L[i][j] 的 LCS。設 Si−1,jS_{i-1, j} 為前綴 (i−1,j)(i-1, j) 的相異 LCS 集合,Si,j−1S_{i, j-1} 為前綴 (i,j−1)(i, j-1) 的相異 LCS 集合。
    根據排容原理,聯集大小為 ∣Si−1,j∪Si,j−1∣=∣Si−1,j∣+∣Si,j−1∣−∣Si−1,j∩Si,j−1∣|S_{i-1, j} \cup S_{i, j-1}| = |S_{i-1, j}| + |S_{i, j-1}| - |S_{i-1, j} \cap S_{i, j-1}|。

🔒

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

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

免費註冊

第 23 題4 分

  1. (4 points) Consider the linked list representation of disjoint sets, where: (1) Each set is represented by a linked list. (2) Each element stores a pointer to its set representative. (3) UNION(x, y) appends the shorter list to the longer list (union by size). (4) FIND-SET(x) returns an element's representative. Consider a sequence of mm legal union and find-set operations on nn elements, starting from an empty state with the first operation being UNION. Which of the following statements is correct?

(A) The total time for all UNION operations is O(n2)O(n^2), regardless of how unions are ordered.
(B) The total running time of all operations is O(nlog⁡n)O(n \log n), because FIND-SET dominates.
(C) Using union by size makes UNION amortized O(1)O(1), yielding total time O(m+n)O(m+n).
(D) The total time of all operations is O(m+n)O(m+n), because each operation touches at most a constant number of elements.
(E) Each element's representative pointer can be updated at most log⁡n\log n times, so all UNION operations take O(nlog⁡n)O(n \log n) time in total.

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

這一題的完整詳解

核心觀念

本題考查資料結構中**不相交集(Disjoint-Set / Union-Find)的鏈結串列表示法(Linked-List Representation)及其加權合併啟發式策略(Weighted-Union Heuristic / Union by Size)**的時間複雜度分析。

  1. 鏈結串列表示法:
    • 每個集合由一個單向鏈結串列表示,串列的首節點即為該集合的代表元(Representative)。
    • 集合內的每個元素皆包含一個指向首節點(代表元)的指標。
  2. 操作複雜度特性:
    • FIND-SET(x)\text{FIND-SET}(x):直接存取 xx 所儲存的代表元指標,時間複雜度為 O(1)O(1)。
    • UNION(x,y)\text{UNION}(x, y):將包含 xx 與包含 yy 的兩個串列合併。合併時必須遍歷較短的串列,將其中所有元素的代表元指標更新為較長串列的首節點。

解題方法

分析使用「依大小合併(Union by Size)」時,代表元指標被更新的總次數上限:

  1. 單一元素指標更新條件:當元素 xx 的代表元指標被更新時,代表 xx 原本所在的集合為較短的串列(設大小為 kk),並被併入另一個長度至少為 kk 的較長串列中。
  2. 集合大小倍增:合併完成後,包含 xx 的新集合大小至少變為原本的 22 倍(即新大小 ≥2k\ge 2k)。
  3. 更新次數上限:由於全部共有 nn 個元素,合併後集合的最大可能大小為 nn。元素 xx 初始所在集合大小至少為 11,經過 cc 次代表元指標更新後,其所在集合大小至少為 2c2^c。因此:
    2c≤n  ⟹  c≤log⁡2n2^c \le n \implies c \le \log_2 n
    即任何單一元素的代表元指標在整個過程中至多被更新 ⌊log⁡2n⌋\lfloor \log_2 n \rfloor 次。
  4. 全體 UNION 總耗時:因為共有 nn 個元素,所有 nn 個元素的代表元指標更新總次數上限為:
    n⋅⌊log⁡2n⌋=O(nlog⁡n)n \cdot \lfloor \log_2 n \rfloor = O(n \log n)
    故在 mm 次操作的序列中,所有 UNION\text{UNION} 操作維護指標的累計時間為 O(nlog⁡n)O(n \log n)。
  5. 整體時間複雜度:mm 次操作中,FIND-SET\text{FIND-SET} 每次耗時 O(1)O(1),共耗時 O(m)O(m);UNION\text{UNION} 操作總共耗時 O(nlog⁡n)O(n \log n)。
🔒

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

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

免費註冊

第 24 題4 分

  1. (4 points) Let G=(V,E)G = (V, E) be a directed graph represented using adjacency lists, where VV is the set of vertices and EE is the set of edges. A standard Breadth-First Search (BFS) is run from a source vertex ss, producing distance labels d[u]d[u] for all reachable vertices u∈Vu \in V. Which of the following statements is always true?

(A) For every edge (u,v)∈E(u, v) \in E, we must have d[u]≤d[v]+1d[u] \leq d[v] + 1.
(B) If d[u]=d[v]+1d[u] = d[v] + 1, then (u,v)(u, v) is a tree edge in the BFS tree.
(C) In a directed graph, BFS always produces a shortest-path tree that is also a topological ordering of the reducible graph.
(D) If the graph is represented by an adjacency matrix instead of adjacency lists, BFS may compute incorrect distances due to repeated edge relaxations.
(E) If we disconnect vertices in the order v1,v2,…,vnv_1, v_2, \dots, v_n, then this order is a shortest-path ordering for all pairs of vertices.

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

這一題的完整詳解

答案:(E)

說明

BFS 從起點 ss 開始,使用佇列逐層擴展。第一次發現 (discover) 或第一次從佇列中「抽出」的頂點,其距離標籤 d[u]d[u] 已確定且等於最短路徑長度。佇列的 FIFO 特性保證了頂點被抽出的順序是 非遞減的距離序,即

d[v1]≤d[v2]≤⋯≤d[vn].d[v_1]\le d[v_2]\le\dots\le d[v_n].

因此以此順序斷開(或移除)頂點時,已經得到一個 從起點出發的最短路徑序;對於每一個頂點 viv_i,其到 ss 的最短路徑已在之前的頂點中完整確立。此性質僅對 BFS 從單一源點而言成立,題目只要說「最短路徑排序」即可接受。


其他選項為偽

🔒

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

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

免費註冊

第 25 題4 分

  1. (4 points) Let G=(V,E)G = (V, E) be a connected, undirected graph with distinct and positive edge weights. Let A⊂EA \subset E be a subset of edges that is contained in some minimum spanning tree of GG. Which of the following statements is always true?

(A) Any minimum-weight edge in the graph is safe for AA.
(B) For any cut (S,V∖S)(S, V \setminus S), the lightest edge crossing the cut is safe for AA, regardless of whether the cut respects AA.
(C) If an edge ee is the lightest edge on some cycle in GG, then ee must belong to every minimum spanning tree (MST) of GG.
(D) If (S,V∖S)(S, V \setminus S) respects AA, then the lightest edge crossing this cut is safe for AA.
(E) Any edge chosen by Prim's algorithm from an arbitrary start vertex is safe for every subset A⊂EA \subset E.

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

這一題的完整詳解

核心觀念

本題考查圖論中**最小生成樹(Minimum Spanning Tree, MST)的經典理論,特別是 CLRS《演算法導論》中所定義的切邊定理(Cut Theorem / Safe Edge Theorem)與安全邊(Safe Edge)**的性質。

在邊權重皆為正且互不相同的連通無向圖 G=(V,E)G = (V, E) 中:

  1. 安全邊(Safe Edge)的定義:
    設邊集合 A⊂EA \subset E 包含於 GG 的某個 MST 中。若存在邊 e∈E∖Ae \in E \setminus A,使得 A∪{e}A \cup \{e\} 亦包含於 GG 的某個 MST 中,則稱邊 ee 對於 AA 是安全邊(Safe Edge)。
  2. 割(Cut)與尊重(Respect):
    • 無向圖的割 (S,V∖S)(S, V \setminus S) 是將頂點集 VV 劃分為兩個互斥子集 SS 與 V∖SV \setminus S。
    • 若邊集合 A⊂EA \subset E 中沒有任何邊跨越割 (S,V∖S)(S, V \setminus S)(即 AA 中所有邊的兩端點皆同時落在 SS 內或同時落在 V∖SV \setminus S 內),則稱該割尊重(Respects) AA。
    • 跨越割的所有邊中,權重最小者稱為最輕邊(Light Edge)。
  3. 切邊定理(Cut Theorem):
    若 A⊂EA \subset E 包含於某個 MST 中,且割 (S,V∖S)(S, V \setminus S) 尊重 AA,則跨越該割的最輕邊 ee 對於 AA 必定是安全邊。
  4. 環路性質(Cycle Property):
    在任意環路(Cycle)中,**權重最大(最重)的邊絕不可能屬於任何 MST(Red Rule);但環路上權重最小(最輕)**的邊則無此必然保證。

解題方法

本題為概念與定理判斷題,解題切入點如下:

  1. 定理對照:直接對比切邊定理之敘述,確認判定「安全邊」的核心充要前提為割必須「尊重(Respect)」邊集合 AA。
  2. 反例構造:對於涉及「任意(Any)」或「必定(Must)」的強化敘述,利用具體的反例(Counterexample)進行嚴謹排除。

選項分析

  • (A) 錯誤
    全圖中權重最小的邊 emin⁡e_{\min} 雖然必定屬於 MST,但它不一定對「任意子集 AA」都是安全邊。例如:若 AA 已經包含了 emin⁡e_{\min}(即 emin⁡∈Ae_{\min} \in A),則 emin⁡e_{\min} 已在 AA 中,無法作為擴充 AA 的邊;
🔒

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

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

免費註冊

其他考古題

115 年臺灣大學的其他科目

臺灣大學《資料結構與演算法》其他年度