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

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

第 1 題3 分

Let f(n)f(n) be the number of additions in the following algorithm.

for i = 1 to n do
  for j = 1 to i do
    for k = 1 to j do
      C[i][j][k] = A[i][j][k] + B[i][j][k];
    end for
  end for
end for
  1. f(n)=O(n2n)f(n) = O(n^2\sqrt{n})
  2. f(n)=O(n2log⁡n)f(n) = O(n^2 \log n)
  3. f(n)=O(n3)f(n) = O(n^3)
  4. f(n)=O(n3log⁡n)f(n) = O(n^3 \log n)
  5. f(n)=O(n100)f(n) = O(n^{100})

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

這一題的完整詳解

核心觀念

本題考查三層巢狀迴圈的執行次數計算,以及漸進上界符號 Big-O(OO) 的嚴格定義:

  • 最內層敘述 C[i][j][k] = A[i][j][k] + B[i][j][k]; 每次執行會進行 11 次加法,因此總加法次數 f(n)f(n) 等於最內層迴圈的總執行次數。
  • 若 f(n)=Θ(n3)f(n) = \Theta(n^3),根據 Big-O 定義(存在常數 c>0c > 0 與 n0n_0,使得對所有 n≥n0n \ge n_0 皆有 0≤f(n)≤c⋅g(n)0 \le f(n) \le c \cdot g(n)),凡是成長速度大於或等於 n3n^3 的函數 g(n)g(n),皆滿足 f(n)=O(g(n))f(n) = O(g(n))。

解題方法

依各層迴圈的上下界列出總加法次數:

  • 外層 ii 從 11 到 nn
  • 中層 jj 從 11 到 ii
  • 內層 kk 從 11 到 jj(執行 jj 次)

因此:

f(n)=∑i=1n∑j=1i∑k=1j1=∑i=1n∑j=1ijf(n) = \sum_{i=1}^{n} \sum_{j=1}^{i} \sum_{k=1}^{j} 1 = \sum_{i=1}^{n} \sum_{j=1}^{i} j

先計算內層等差級數:

∑j=1ij=i(i+1)2\sum_{j=1}^{i} j = \frac{i(i+1)}{2}

再對 ii 加總:

f(n)=∑i=1ni(i+1)2=12(∑i=1ni2+∑i=1ni)f(n) = \sum_{i=1}^{n} \frac{i(i+1)}{2} = \frac{1}{2} \left( \sum_{i=1}^{n} i^2 + \sum_{i=1}^{n} i \right)

代入級數公式 ∑i=1ni2=n(n+1)(2n+1)6\sum_{i=1}^{n} i^2 = \frac{n(n+1)(2n+1)}{6} 與 ∑i=1ni=n(n+1)2\sum_{i=1}^{n} i = \frac{n(n+1)}{2}:

f(n)=12(n(n+1)(2n+1)6+n(n+1)2)=n(n+1)(n+2)6f(n) = \frac{1}{2} \left( \frac{n(n+1)(2n+1)}{6} + \frac{n(n+1)}{2} \right) = \frac{n(n+1)(n+2)}{6}

展開後最高次項為 16n3\frac{1}{6}n^3,故:

f(n)=Θ(n3)f(n) = \Theta(n^3)

選項分析

本題為複選題(須選出所有正確敘述),依 Big-O 定義逐一檢驗:

  1. f(n)=O(n2n)f(n) = O(n^2\sqrt{n})(錯誤)
    n2n=n2.5n^2\sqrt{n} = n^{2.5}。因為 lim⁡n→∞n3n2.5=lim⁡n→∞n0.5=∞\lim_{n\to\infty} \frac{n^3}{n^{2.5}} = \lim_{n\to\infty} n^{0.5} = \infty,n3n^3 的成長速度嚴格高於
🔒

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

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

免費註冊

第 2 題3 分

Given two sorted list A and B (in increasing key order), the following recursive algorithm
merges A and B into a sorted list C (also in increasing key order).
• If either A or B is empty then the result is the other list.
• If both A or B are not empty, we compare the keys of the first nodes of A and B, and select the
smaller one (denoted as s), and remove it from the list. Then we recursively merge the remaining
parts of A and B into a new sorted list C', then we concatenate s with C' into the final sorted list
C.
Let f(n,m)f(n,m) be the minimum number of comparisons of this algorithm, where nn and mm are the numbers
of nodes in A and B respectively. f(n,m)f(n, m) is?

  1. Ω(n)\Omega(n)
  2. Ω(m)\Omega(m)
  3. Ω(n+m)\Omega(n + m)
  4. Ω(mn)\Omega(mn)
  5. Ω(mn(log⁡m+log⁡n))\Omega(mn(\log m + \log n))

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

這一題的完整詳解

核心觀念:兩已排序串列合併(Merge)之最少比較次數分析

  1. 演算法比較機制:

    • 每次比較串列 AA 與 BB 的第一個節點,將較小者 ss 移除後對剩餘部分遞迴合併。
    • 當 AA 或 BB 其中之一為空串列時,直接回傳另一串列,不再進行任何比較(比較次數為 00)。
  2. 最少比較次數 f(n,m)f(n, m) 推導:

    • 每進行 11 次比較,至多從 AA 或 BB 中移除 11 個節點。要使其中一個串列變為空串列,至少必須移除 min⁡(n,m)\min(n, m) 個節點,因此比較次數至少為 min⁡(n,m)\min(n, m)。
    • 若串列 AA 的所有鍵值皆小於 BB 的首節點鍵值,則 AA 的 nn 個節點依序與 BB 的首節點比較共 nn 次後 AA 即為空,演算法結束;同理,若 BB 的所有鍵值皆小於 AA 的首節點鍵值,比較次數為 mm。
    • 故最少比較次數之確切函數為:
      f(n,m)=min⁡(n,m)f(n, m) = \min(n, m)
  3. 各選項漸近下界檢驗:
    依雙變數漸近下界定義,f(n,m)=Ω(g(n,m))f(n, m) = \Omega(g(n, m)) 須存在常數 c>0c > 0 與門檻 n0,m0n_0, m_0,使得對所有 n≥n0,m≥m0n \ge n_0, m \ge m_0 皆有 f(n,m)≥c⋅g(n,m)f(n, m) \ge c \cdot g(n, m)。題目並未對 n,mn, m 的相對大小做任何限制:

🔒

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

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

免費註冊

第 3 題3 分

We now use the merge algorithm in the previous question to sort a set of keys. We first make each key a list of a single node. Then we merge the first and the second lists into a sorted list of length two, the third and the fourth lists into a sorted list of length two, and so on. If we start with nn keys now we have roughly n/2n/2 sorted list of length two now. We then merge these lists of length two into roughly n/4n/4 sorted list of length four, and so on. Finally we will have a sorted list of length nn. Let f(n)f(n) denote the maximum possible total number of comparisons of this algorithm, then f(n)f(n) is? Note that all the answers are in little-o notation.

  1. o(n)o(n)
  2. o(nn)o(n\sqrt{n})
  3. o(nlog⁡n)o(n \log n)
  4. o(n(log⁡n)2)o(n(\log n)^2)
  5. o(n2)o(n^2)

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

這一題的完整詳解

核心觀念

本題考查「由下而上合併排序法(bottom-up merge sort)」在最壞情況下的比較次數,以及漸進符號中小 oo(little-o)的定義。

合併兩個長度分別為 aa 與 bb 的已排序串列時,每次比較會從其中一個串列移出一個元素;當其中一個串列變為空串列時即停止,不再進行比較。最壞情況發生在兩串列交替被取出元素,直到其中一個串列耗盡而另一個串列僅剩 11 個元素,因此最多需要

a+b−1a + b - 1

次比較。特別地,合併兩個長度皆為 mm 的串列,最多需要 2m−12m - 1 次比較。


解題方法

將合併過程依層次分析(設總共有 nn 個鍵值):

  • 第 11 層:將 nn 個長度為 11 的串列兩兩合併為約 n/2n/2 個長度為 22 的串列,每次合併最多 11 次比較,總比較次數為 ⌊n/2⌋=Θ(n)\lfloor n/2 \rfloor = \Theta(n)。
  • 第 22 層:將長度為 22 的串列兩兩合併為約 n/4n/4 個長度為 44 的串列,每次合併最多 33 次比較,總比較次數為 Θ(n)\Theta(n)。
  • 第 kk 層:將長度約為 2k−12^{k-1} 的串列兩兩合併為長度約為 2k2^k 的串列,該層所有合併的總資料量為 nn,因此總比較次數為 Θ(n)\Theta(n)(更精確地,當 n=2mn = 2^m 時,第 kk 層有 2m−k2^{m-k} 次合併,最多比較 2m−k(2k−1)=n−2m−k2^{m-k}(2^k - 1) = n - 2^{m-k} 次)。

串列長度從 11 每次加倍直到 nn,共有 ⌈log⁡2n⌉=Θ(log⁡n)\lceil \log_2 n \rceil = \Theta(\log n) 層,且每層在最壞情況下都可達到 Θ(n)\Theta(n) 次比較,因此:

f(n)=Θ(nlog⁡n).f(n) = \Theta(n \log n).

接著依據小 oo 的定義逐一檢查各選項:

g(n)=o(h(n))  ⟺  lim⁡n→∞g(n)h(n)=0.g(n) = o(h(n)) \iff \lim_{n \to \infty} \frac{g(n)}{h(n)} = 0.

選項分析

選項 1:o(n)o(n)

錯誤。因為

lim⁡n→∞f(n)n=lim⁡n→∞Θ(log⁡n)=∞≠0,\lim_{n \to \infty} \frac{f(n)}{n} = \lim_{n \to \infty} \Theta(\log n) = \infty \neq 0,

所以 f(n)f(n) 不是 o(n)o(n)。


選項 2:o(nn)o(n\sqrt{n})

正確。因為

lim⁡n→∞f(n)nn=lim⁡n→∞Θ(log⁡nn)=0,\lim_{n \to \infty} \frac{f(n)}{n\sqrt{n}} = \lim_{n \to \infty} \Theta\left(\frac{\log n}{\sqrt{n}}\right) = 0,

(由羅必達法則,lim⁡n→∞1/(nln⁡2)12n−1/2=lim⁡n→∞2(ln⁡2)n=0\lim_{n \to \infty} \frac{1/(n\ln 2)}{\frac{1}{2}n^{-1/2}} = \lim_{n \to \infty} \frac{2}{(\ln 2)\sqrt{n}} = 0),因此 f(n)=o(nn)f(n) = o(n\sqrt{n})。


🔒

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

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

免費註冊

第 4 題3 分

A binary minimum heap is a binary tree in which every level is completely full, except the
last level, which is filled from the left to right. Here the level of a node is its distance to the root, so the
root has level 0 and the children of the root will have level 1, and so on. Also the key of a parent is less
than those of its children. For ease of discussion we assume that all keys in the heap are distinct. Now
which of the following descriptions about a binary minimum heap of 10 nodes (see the figure below) are
correct?
🖼️【此處有附圖,請對照原卷】

  1. The second smallest key is always in level 1.
  2. The largest key is always in a leaf, i.e., a node without any children.
  3. The second largest key is always in a leaf.
  4. Let nn be the number of nodes and we consider the case of arbitrary nn, then the height of the tree
    is O(log⁡n)O(\log n).
  5. Let nn be the number of nodes and we consider the case of arbitrary nn, then we can find the third
    smallest key of the heap by O(1)O(1) key comparisons.
🖼️ 本題含圖表,以下為原卷對應頁面:
原卷第 2 頁

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

這一題的完整詳解

核心觀念

最小堆同時滿足兩個條件:

  • 形狀性質:除了最底層外,各層都填滿;最底層由左至右填入。
  • 堆序性質:每個父節點的鍵值都小於其子節點。題目又說鍵值互異,因此大小關係明確。

堆序性質也會沿著路徑傳遞:任一祖先的鍵值都小於其後代。

解題方法

第 1、2、3、5 項利用堆序性質判斷鍵值可能的位置;第 4 項則利用完全二元樹的高度界。判斷「第二大」時,還要留意最底層由左至右填入後,某些非葉節點可能只有一個子節點。

選項分析

  1. 正確。 根節點是最小值。第二小的鍵值必在根的子節點中:任何更深的節點,都有一個根的子節點作為祖先,而該子節點的鍵值更小。因此,比較根的兩個子節點即可找出第二小值;此堆有 10 個節點,根有兩個子節點。

  2. 正確。 若最大值位於非葉節點,該節點至少有一個子節點,而子節點鍵值必比它大,與它是最大值矛盾。因此最大值必在葉節點。

  3. 錯誤。 此堆最底層從左至右填入 3 個節點,因此有一個非葉節點只有一個子節點。可將節點鍵值依層序排列為

    1, 2, 3, 4, 9, 5, 6, 7, 8, 101,\ 2,\ 3,\ 4,\ 9,\ 5,\ 6,\ 7,\ 8,\ 10

    每個父節點都小於子節點,符合最小堆條件;其中鍵值 9 是第二大值,卻位於有一個子節點的非葉節點。因此第二大值不一定在葉節點。

🔒

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

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

免費註冊

第 5 題3 分

We will follow the notations from the previous question. We can build a heap from an array
of n keys by the following algorithm. A heapify operation for a binary minimum heap combines two
heaps and a root into a new heap. For ease of discussion we assume that the array is indexed from 1
to n, and the left/right child of a node with array index i have array indices 2i and 2i + 1 respectively.
We first set each key of the second half of the array (indexed from n/2 to n) as n/2 heaps, each has one
node. Then we combine two of them and their parent into a heap of three nodes, and so on. If the root
is smaller than the roots of both subtrees then we stop. Otherwise we exchange the root with the smaller
root from the subtrees, and repeatedly heapify the subtree where the root has just been replaced. Next
we heapify the key at n/2-1 and all the way back to the root (at index 1). The final result will be a
binary minimum heap of n nodes.

  1. The minimum number of key comparisons is O(n)O(n).
  2. The maximum number of key comparisons is O(n)O(n).
  3. Since each heapify on a key may compare it with all the keys down to a leaf, its number of
    comparisons is no more than the height of the heap, which is O(log⁡n)O(\log n). Also we have O(n)O(n) keys to
    heapify, so the total number of key comparisons is O(nlog⁡n)O(n \log n).
  4. The number of key comparisons is in the same order as the sum of (original, before heapified) levels
    (as defined in the previous question, the distance to the root) of all keys.

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

這一題的完整詳解

核心觀念

本題考查由下而上建立二元堆積(Bottom-Up Build-Heap / Floyd's Algorithm)​的比較次數與時間複雜度分析,核心概念包含:

  1. 堆積調整(Heapify / Sift-Down)之成本:
    在高度為 hh 的節點上執行一次 Heapify,其元素最多往下沉 hh 層。每下沉一層需要先比較左右子節點(1 次比較),再將較小(或較大)者與當前父節點比較(1 次比較),因此單層至多需要 22 次鍵值比較。故在高度為 hh 的節點執行 Heapify,比較次數上界為 O(h)O(h)。
  2. 節點高度(Height)與節點深度/層級(Depth / Level)的區別:
    • 高度(Height, hh):節點到其子樹中最遠葉節點的路徑長度(葉節點 h=0h=0)。
    • 深度/層級(Depth / Level, dd):根節點到該節點的路徑長度(根節點 d=0d=0)。
    • 由下而上建堆的比較次數與各節點的高度總和(Sum of Heights)​成正比,而非深度總和(Sum of Depths)。
  3. 收斂級數求和:
    計算最差情況時,利用等比差級數求和公式: ∑h=1∞h2h=2\sum_{h=1}^{\infty} \frac{h}{2^h} = 2 證明 Bottom-Up 建堆的總比較次數在最差情況下為 Θ(n)=O(n)\Theta(n) = O(n)。

解題方法與數學推導

1. 最佳情況(Best-Case)分析

  • 情境:若輸入陣列本來就已經滿足 Min-Heap 的性質(例如所有節點皆小於其子節點)。
  • 推導:
    演算法依序對 index ⌊n/2⌋\lfloor n/2 \rfloor 遞減至 11 的所有內部節點進行 Heapify。每個內部節點在比較左右子節點並與根比較後,發現根節點已是最小值,即立刻停止下沉(下沉深度為 0)。
    共有 ⌊n/2⌋\lfloor n/2 \rfloor 個內部節點,每個節點固定做 1∼21 \sim 2 次比較: Tmin⁡(n)≥1×⌊n2⌋=Ω(n)T_{\min}(n) \ge 1 \times \left\lfloor \frac{n}{2} \right\rfloor = \Omega(n) 因此最佳情況的比較次數為 Θ(n)\Theta(n),滿足 O(n)O(n)。

2. 最差情況(Worst-Case)分析

  • 情境:每次 Heapify 的節點都需要一路下沉至葉節點。
  • 推導:
    在包含 nn 個節點的完全二元樹中,高度為 hh 的節點數量上限為 ⌈n2h+1⌉\left\lceil \frac{n}{2^{h+1}} \right\rceil,樹高為 ⌊log⁡2n⌋\lfloor \log_2 n \rfloor。
    每個高度為 hh 的節點最多進行 2h2h 次比較,總比較次數 Tmax⁡(n)T_{\max}(n) 滿足: Tmax⁡(n)≤∑h=1⌊log⁡2n⌋⌈n2h+1⌉⋅2h≤∑h=1∞n2h⋅h=n∑h=1∞h2hT_{\max}(n) \le \sum_{h=1}^{\lfloor \log_2 n \rfloor} \left\lceil \frac{n}{2^{h+1}} \right\rceil \cdot 2h \le \sum_{h=1}^{\infty} \frac{n}{2^h} \cdot h = n \sum_{h=1}^{\infty} \frac{h}{2^h} 令 S=∑h=1∞h2h=12+24+38+416+…S = \sum_{h=1}^{\infty} \frac{h}{2^h} = \frac{1}{2} + \frac{2}{4} + \frac{3}{8} + \frac{4}{16} + \dots
    將兩邊同乘 12\frac{1}{2}: 12S=14+28+316+…\frac{1}{2}S = \frac{1}{4} + \frac{2}{8} + \frac{3}{16} + \dots 兩式相減: S−12S=12+14+18+116+⋯=1  ⟹  S=2S - \frac{1}{2}S = \frac{1}{2} + \frac{1}{4} + \frac{1}{8} + \frac{1}{16} + \dots = 1 \implies S = 2 代回得: Tmax⁡(n)≤2n=O(n)T_{\max}(n) \le 2n = O(n) 因此最差情況下的鍵值比較次數為 Θ(n)=O(n)\Theta(n) = O(n)。

3. 高度總和 vs. 深度/層級總和

  • 各節點高度之和(Sum of Heights): ∑v∈Theight(v)=∑h=0⌊log⁡2n⌋h⋅⌈n2h+1⌉=Θ(n)\sum_{v \in T} \text{height}(v) = \sum_{h=0}^{\lfloor \log_2 n \rfloor} h \cdot \left\lceil \frac{n}{2^{h+1}} \right\rceil = \Theta(n) Bottom-Up 建堆的總比較次數直接由節點的高度決定,故與高度之和同階(Θ(n)\Theta(n))。
  • 各節點層級/深度之和(Sum of Depths/Levels): ∑v∈Tdepth(v)=∑d=0⌊log⁡2n⌋d⋅2d=Θ(nlog⁡n)\sum_{v \in T} \text{depth}(v) = \sum_{d=0}^{\lfloor \log_2 n \rfloor} d \cdot 2^d = \Theta(n \log n) 若採用由上而下(Top-Down)逐一將元素 Insert 入堆積,每次插入上浮的距離受限於該節點的深度(Level),總成本才會是 Θ(nlog⁡n)\Theta(n \log n)。

選項分析

🔒

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

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

免費註冊

第 6 題3 分

A randomized quick sort works as follows. For ease of discussion we assume that the sequence we want to sort, K=(k1,…,kn)K = (k_1, \dots, k_n), is a permutation of 11 to nn. We randomly and uniformly pick a key kk from KK. Then we partition KK into two subsets – K1K_1 that has keys less than kk and K2K_2 that has keys greater than kk. Then we recursively sort K1K_1 and K2K_2, and combine the results with kk to get the sorted sequence.

  1. The number of key comparisons will always be maximized when the keys in KK are already sorted.
  2. Let ∣K1∣|K_1| and ∣K2∣|K_2| be the number of keys in K1K_1 and K2K_2 respectively. The expected value of max⁡(∣K1∣,∣K2∣)\max(|K_1|, |K_2|) is 23n\frac{2}{3}n.
  3. The algorithm will compare two keys kik_i and kjk_j at most once, so the number of key comparisons is O(n2)O(n^2).
  4. The probability that the algorithm will compare kik_i and kjk_j (n≥i>j≥1n \ge i > j \ge 1) is 2i−j+1\frac{2}{i - j + 1}.
  5. Let P={(i,j)∣1≤i,j≤n,i≠j}P = \{(i, j) \mid 1 \le i, j \le n, i \neq j\}. The expected total number of key comparisons is ∑(i,j)∈P1∣ki−kj∣+1\sum_{(i,j) \in P} \frac{1}{|k_i - k_j| + 1}.

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

這一題的完整詳解

各選項詳細分析如下:

  1. 錯誤。隨機快速排序(Randomized Quick Sort)的樞紐(pivot)是從 KK 中隨機均勻選取,因此比較次數的機率分佈與輸入序列 KK 的初始排列無關;即使 KK 已經排序完成,只要隨機選到較平衡的樞紐,比較次數仍可能為 O(nlog⁡n)O(n \log n),不會總是達到最大值。

  2. 錯誤。設選到的樞紐為 k=r∈{1,2,…,n}k = r \in \{1, 2, \dots, n\},每個值被選中的機率皆為 1n\frac{1}{n},此時兩子集合大小分別為 ∣K1∣=r−1|K_1| = r - 1 與 ∣K2∣=n−r|K_2| = n - r。期望值計算如下:
    E[max⁡(∣K1∣,∣K2∣)]=1n∑r=1nmax⁡(r−1,n−r)={34n−12,n 為偶數34n−12−14n,n 為奇數E[\max(|K_1|, |K_2|)] = \frac{1}{n} \sum_{r=1}^{n} \max(r - 1, n - r) = \begin{cases} \frac{3}{4}n - \frac{1}{2}, & n \text{ 為偶數} \\ \frac{3}{4}n - \frac{1}{2} - \frac{1}{4n}, & n \text{ 為奇數} \end{cases}
    當 nn 很大時漸近於 34n\frac{3}{4}n,而非 23n\frac{2}{3}n(例如 n=2n = 2 時期望值為 1≠431 \neq \frac{4}{3})。

  3. 正確。演算法僅在分割(partition)階段將當前樞紐 kk 與同子集合中的其餘元素各比較一次;一旦某元素被選為樞紐,該元素即定位並不再進入後續的 K1K_1 或 K2K_2 遞迴。因此任意兩相異鍵值 kik_i 與 kjk_j 至多只會被比較一次。全體鍵值對數為 (n2)=n(n−1)2\binom{n}{2} = \frac{n(n-1)}{2},故總比較次數必為 O(n2)O(n^2)。

  4. 錯誤。序列 K=(k1,…,kn)K = (k_1, \dots, k_n) 是 11 到 nn 的一個排列,i,ji, j 是位置索引(index),而 ki,kjk_i, k_j 才是鍵值(key value)。

🔒

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

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

免費註冊

第 7 題3 分

We can use a linked list to implement a stack. We assume that we use structure Node with two members to represent a node of the linked list. The member data stores the data, and the member next points to the next node in the linked list. Also we use a variable head to point to the first node of the linked list. head is initialized to NULL.

  1. Pushing the value of a variable i into the stack can be implemented as follows.
    newHead = malloc(sizeof(Node));
    newHead->data = i;
    newHead->next = head;
    head = newHead;
  2. Popping the top of the stack into a variable i can be implemented as follows.
    free(head);
    i = head->data;
    head = head->next;
  3. To test if the stack is empty we can check if the head is a NULL pointer.
  4. We can improve the push/pop efficiency of this stack by adding another pointer tail that points to the end of the linked list, so we can access the last node in the list in O(1) time.
  5. We can improve the push/pop efficiency of this stack by adding another pointer member into every node, so it becomes a double linked list. That is, we can traverse in both directions in this linked list.

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

這一題的完整詳解

核心觀念

本題考查:

  • Linked list 實作 Stack 的方式
  • Stack 的 LIFO(Last-In, First-Out)
  • Push 與 pop 的時間複雜度
  • 指標操作與動態記憶體管理
  • Singly linked list 與 doubly linked list 的差異

以 head 指向 linked list 第一個節點時,最適合將 head 視為 stack 的頂端:

  • Push:將新節點插入 head 前方
  • Pop:移除 head 所指的節點
  • Empty:檢查 head == NULL

因此 push 與 pop 都能在 O(1)O(1) 時間完成。


解題方法

逐一檢查每個敘述:

  1. 是否正確維持 stack 的 LIFO 結構?
  2. 是否正確操作 linked list 指標?
  3. 是否有違反 C 語言動態記憶體使用規則?
  4. 是否真的改善了時間複雜度?

選項分析

1. Push 實作

newHead = malloc(sizeof(Node));
newHead->data = i;
newHead->next = head;
head = newHead;

此敘述正確。

原本 stack:

示意圖

建立新節點後:

示意圖

令:

newHead->next = head;

得到:

示意圖

最後:

head = newHead;

新的節點成為 stack top,符合 LIFO。

時間複雜度為:

Tpush=O(1)T_{\text{push}} = O(1)

空間複雜度為:

O(1)O(1)

其中 O(1)O(1) 是指此次 push 額外配置一個節點。


2. Pop 實作

free(head);
i = head->data;
head = head->next;

此敘述錯誤。

free(head) 會釋放 head 所指向的記憶體。釋放後,head 仍可能保留原本的位址,但該位址已經不能再存取,因此後續:

i = head->data;
head = head->next;

都是對已釋放記憶體的存取,屬於 use-after-free,會造成未定義行為。

正確順序應為:

i = head->data;
oldHead = head;
head = head->next;
free(oldHead);

也可寫成:

i = head->data;
Node *oldHead = head;
head = head->next;
free(oldHead);

若要處理空 stack,還必須先檢查:

if (head == NULL) {
    /* stack underflow */
}

正確 pop 的時間複雜度為:

Tpop=O(1)T_{\text{pop}} = O(1)

3. 判斷 stack 是否為空

檢查:

head == NULL

此敘述正確。

當 linked list 沒有任何節點時:

🔒

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

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

免費註冊

第 8 題3 分

A randomized linked list sorting algorithm works as follows. We want to build a linked list in which the keys are in increasing order. That is, every node has a smaller key than its successor in the list. For ease of discussion we assume that the keys are distinct integers from 1 to n. The algorithm randomly picks a key from the remaining keys, and inserts it into the list. This process repeats until all keys are inserted. The inserted key k will skip those at the beginning of the list that are smaller than it, and will stop at the first key p that are greater than it. We then insert the key k before p. To ensure that all keys will stop we assume that initially the list has only one key, n + 1. After we insert all keys we will have a sorted linked list from 1 to n + 1.

  1. Every inserted key will stop exactly once.
  2. The smallest key 1 will not skip any keys.
  3. The largest key n will always skip n - 1 keys.
  4. The expected number of keys that the key i will skip is Ω(i)\Omega(i).
  5. The key i will skip j if and only if i > j and i is inserted after j is inserted, so the expected value of the total number of key comparisons is Θ(n2)\Theta(n^2).

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

這一題的完整詳解

核心觀念

本題考查隨機插入排序(randomized insertion into a linked list)的正確性與期望比較次數分析。

串列初始含有哨兵鍵(sentinel key)n+1n+1,且每次插入都將鍵 k∈{1,2,…,n}k \in \{1, 2, \dots, n\} 放在第一個大於 kk 的鍵之前,因此串列始終維持嚴格遞增順序。


解題方法

由於演算法每次從剩餘鍵中隨機等機率挑選一個鍵插入,這等價於 1,2,…,n1, 2, \dots, n 的插入順序為一個均勻隨機排列(uniform random permutation)。

考慮任一鍵 i∈{1,2,…,n}i \in \{1, 2, \dots, n\} 在插入時會跳過的鍵數 XiX_i:

  • 若鍵 j<ij < i 先於 ii 插入,則 ii 插入時 jj 已在串列中且位於所有大於 ii 的鍵之前,故 ii 必定會跳過 jj。
  • 若鍵 j>ij > i(包含哨兵 n+1n+1),或 j<ij < i 但 jj 晚於 ii 插入,則 ii 不可能跳過 jj。

因此,對任意 1≤j<i1 \le j < i,定義指示隨機變數 Ij,i=1I_{j,i} = 1 若 jj 先於 ii 插入,否則為 00。在均勻隨機排列中,P(j 先於 i)=12P(j \text{ 先於 } i) = \frac{1}{2},由期望值線性性可得:

E[Xi]=∑j=1i−1E[Ij,i]=∑j=1i−112=i−12.E[X_i] = \sum_{j=1}^{i-1} E[I_{j,i}] = \sum_{j=1}^{i-1} \frac{1}{2} = \frac{i-1}{2}.

每次插入鍵 ii 除了與被跳過的 XiX_i 個鍵比較外,還會與第一個大於 ii 的鍵(最壞情況為哨兵 n+1n+1)比較 11 次後才停止。因此總比較次數為:

C=∑i=1n(Xi+1)=n+∑i=1nXi.C = \sum_{i=1}^{n} (X_i + 1) = n + \sum_{i=1}^{n} X_i.

取期望值:

E[C]=n+∑i=1ni−12=n+n(n−1)4=n2+3n4=Θ(n2).E[C] = n + \sum_{i=1}^{n} \frac{i-1}{2} = n + \frac{n(n-1)}{4} = \frac{n^2 + 3n}{4} = \Theta(n^2).

選項分析

1. Every inserted key will stop exactly once.

正確。 因為初始串列含有哨兵鍵 n+1n+1,且所有待插入的鍵 k∈{1,…,n}k \in \{1, \dots, n\} 皆滿足 k<n+1k < n+1。每次插入 kk 時,搜尋由串列開頭出發,必定會在第一個大於 kk 的鍵處(至多在 n+1n+1 處)停止,並將 kk 插入其前方,結束該次插入操作。故每個被插入的鍵恰會停止一次。

2. The smallest key 1 will not skip any keys.

正確。 鍵 11 是所有鍵中的最小值,無論何時插入,串列中所有已存在的鍵(包含 n+1n+1)都大於 11。因此搜尋在串列的第一個節點就會停止,跳過的鍵數 X1=0X_1 = 0。

3. The largest key n will always skip n - 1 keys.

🔒

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

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

免費註冊

第 9 題3 分

A binary search tree is a tree where every node has at most two children. For ease of discussion we assume that every node has a distinct key. In addition, all keys in the left subtree are smaller than the key of root, and all keys in the right subtree are larger than the key of the root. A tree node is a leaf if it does not have any children. The height of the tree is the length of the longest path from the root to a leaf. The successor of a node xx is the node right after xx in increasing order, and the predecessor of a node xx is the node right before xx in increasing order.

  1. We can locate the smallest key in a binary search tree in O(h)O(h) time in the worst case, where hh is the height of the tree.
  2. The height of a binary search tree of nn nodes is O(log⁡n)O(\log n).
  3. We can locate the largest key in a binary search tree in O(log⁡n)O(\log n) time in the worst case, where nn is the number of the nodes in the tree.
  4. Assume that a node zz has two children. We can remove zz while still maintaining the sorted order by locating its successor yy, connecting yy's parent directly to the only child of yy (if there is one, otherwise make it null), which effectively removes the node yy from the tree, and replacing the key of zz with that of yy.
  5. Assume that a node zz has two children. We can remove zz while still maintaining the sorted order by locating its predecessor yy, connecting yy's parent directly to the only child of yy (if there is one, otherwise make it null), which effectively removes the node yy from the tree, and replacing the key of zz with that of yy.

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

這一題的完整詳解

核心觀念

本題考查二元搜尋樹(Binary Search Tree, BST)的:

  • 搜尋最小值與最大值的方法及時間複雜度。
  • 樹高與節點數的關係。
  • 使用 successor(後繼)或 predecessor(前驅)刪除具有兩個子樹的節點。
  • BST 的排序性質:
左子樹所有鍵值<根節點鍵值<右子樹所有鍵值\text{左子樹所有鍵值} < \text{根節點鍵值} < \text{右子樹所有鍵值}

BST 的中序走訪結果會依鍵值遞增排列,因此 successor 是中序順序的下一個節點,predecessor 是中序順序的上一個節點。


解題方法

判斷搜尋複雜度時,沿著樹的一條路徑向下尋找,因此時間複雜度通常為 O(h)O(h),其中 hh 是樹高。只有在樹高本身為 O(log⁡n)O(\log n) 時,才能進一步寫成 O(log⁡n)O(\log n)。

刪除具有兩個子女的節點時,可用其中序後繼或中序前驅的鍵值取代該節點,再刪除後繼或前驅原本所在的節點。這是因為:

  • successor 位於右子樹中最左側的位置,因此沒有左子女,最多只有右子女。
  • predecessor 位於左子樹中最右側的位置,因此沒有右子女,最多只有左子女。

所以被移除的 successor 或 predecessor 一定至多只有一個子女,能以一般的「單子女節點刪除」方式處理。


選項分析

1. 正確

BST 中最小鍵值必定位於最左側。從根節點開始,不斷沿著 left pointer 往下走,直到目前節點沒有左子女為止:

最小鍵值節點=最左側節點\text{最小鍵值節點} = \text{最左側節點}

最多走過從根到葉節點的一條路徑,因此最壞時間複雜度為:

O(h)O(h)

所以此敘述正確。


2. 錯誤

一般二元搜尋樹不保證平衡。若每次插入的鍵值都比前一個大,例如依序插入:

1,2,3,…,n1,2,3,\ldots,n

形成的 BST 會退化成鏈狀:

1→2→3→⋯→n1 \rightarrow 2 \rightarrow 3 \rightarrow \cdots \rightarrow n

此時樹高為:

h=n−1=O(n)h=n-1=O(n)

只有平衡二元搜尋樹的高度才是 O(log⁡n)O(\log n))。一般 BST 的高度最壞情況為 O(n)O(n),因此此敘述錯誤。


3. 錯誤

最大鍵值必定位於最右側。搜尋最大值的方法是從根節點開始,不斷沿著 right pointer 往下走,因此時間複雜度為:

O(h)O(h)

雖然在平衡 BST 中 h=O(log⁡n)h=O(\log n),但題目沒有保證 BST 平衡。退化成鏈狀時:

h=O(n)h=O(n)

所以搜尋最大值的最壞時間複雜度是 O(n)O(n),不能保證為 O(log⁡n)O(\log n)。此敘述錯誤。


4. 正確

假設節點 zz 有左、右兩個子樹。令 yy 為 zz 的 successor。

因為 yy 是 zz 的右子樹中最小的節點,所以 yy 不可能有左子女;否則其左子女會比 yy 更小。故 yy 最多只有右子女。

刪除步驟如下:

🔒

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

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

免費註冊

第 10 題3 分

A red-black tree is a binary tree where every node has a color (red or black), and has the
following properties.

  1. The root is black.
  2. All paths from the root to a leaf have the same number of black nodes.
  3. Every red node must have two black children.
    For ease of discussion we assume that all null pointers (a special pointer to "nothing") point to a special
    black node. As a result all counting of the second property ends at this special node.
  4. If we do not guarantee the first property, but still guarantee the second and the third properties,
    we will not be able to guarantee that the height of the tree is O(log⁡n)O(\log n).
  5. It is possible that there are no red nodes in a red-black tree of 100000 nodes.
  6. We insert a key k into a non-empty red-black tree just like into an ordinary binary search tree as
    a leaf, attach to it two null pointers to the special black node, and then immediately stop without
    any adjustment. If we color k red, we may violate the second property above.
  7. Consider the scenario above. If we color k red, we may violate the third property above.
  8. Consider the scenario above. If we color k black, we will violate the second property above.

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

這一題的完整詳解

各選項詳細推導如下:

  1. 錯誤。若根節點改為紅色,但仍維持屬性 2(所有路徑黑節點數相同)與屬性 3(無連續紅節點),設黑高度為 bhbh。由於紅節點不得連續,樹高滿足 h≤2⋅bh+1h \le 2 \cdot bh + 1。又由黑色節點構成的樹結構可知內部節點數 n≥2bh−1  ⟹  bh≤log⁡2(n+1)n \ge 2^{bh} - 1 \implies bh \le \log_2(n+1),故樹高仍保證為 h≤2log⁡2(n+1)+1=O(log⁡n)h \le 2\log_2(n+1) + 1 = O(\log n)。

  2. 錯誤。若紅黑樹中無任何紅節點,則所有節點皆為黑節點。根據屬性 2,從根節點到每個 NULL 節點的路徑黑節點數必須相等,即所有路徑長度皆為 hh,此樹必為完美二元樹(Perfect Binary Tree)。其內部節點總數必須符合 n=2h−1n = 2^h - 1。因為 100000≠2h−1100000 \neq 2^h - 1(216−1=655352^{16}-1 = 65535,217−1=1310712^{17}-1 = 131071),故不可能存在 100000 個節點且無紅節點的紅黑樹。

🔒

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

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

免費註冊

第 11 題5 分

Given an array of n integers A = (a1,a2,...,ana_1, a_2, ..., a_n) (n>0n > 0), you are asked to find the maximum
and minimum elements with minimum comparisons. A simple solution is to iteratively compare each
element with current max and min. It takes 2n comparisons in total.
(a) (3 points) Devise an algorithm that requires less than 1.67n comparisons.
(b) (2 points) How many comparisons does your algorithm take? Show your derivation.

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

這一題的完整詳解

核心觀念

這題考的是「成對比較(pairwise comparison)」找最大值與最小值。

若逐一處理每個元素,每個元素都必須分別與目前最大值、最小值比較,約需 2n2n 次比較。改進方法是先把元素兩兩分組:

  1. 先比較同一對中的兩個元素,判定誰較小、誰較大。
  2. 較小者只需與目前最小值比較。
  3. 較大者只需與目前最大值比較。

因此,每一對元素只需 33 次比較,而不是 44 次。


解題方法

將陣列分成若干組,每組包含兩個元素。對於一組 (x,y)(x,y):

  • 若 x<yx<y,則令 low=xlow=x、high=yhigh=y;
  • 否則令 low=ylow=y、high=xhigh=x。

接著執行:

  • 比較 lowlow 與目前的最小值;
  • 比較 highhigh 與目前的最大值。

如此每處理一對元素,固定使用 33 次比較。

關鍵虛擬碼如下:

if n = 1:
    min = max = A[1]

else if n is even:
    compare A[1] and A[2]
    initialize min and max
    i = 3

else:
    min = max = A[1]
    i = 2

while i <= n:
    compare A[i] and A[i+1]
    let low be the smaller element
    let high be the larger element

    compare low with min
    compare high with max

    i = i + 2

return min, max

若一對元素相等,任意指定其中一個為 lowlow、另一個為 highhigh,仍不影響正確性。


正確性說明

處理完每一對元素後,該對的較小元素一定不可能成為整體最大值,因此只需拿來更新最小值;同理,該對的較大元素一定不可能成為整體最小值,因此只需拿來更新最大值。

維持以下不變量:

  • min 是目前已處理元素中的最小值;
  • max 是目前已處理元素中的最大值。

每處理一對新元素後:

  • 較小者與 min 比較,確保最小值正確;
  • 較大者與 max 比較,確保最大值正確。

所有元素處理完畢後,min 與 max 即為整個陣列的最小值與最大值。


比較次數推導

情況一:nn 為偶數

先比較 A1A_1 與 A2A_2 以初始化最大值與最小值,需 11 次比較。

剩下 n−2n-2 個元素,共形成

n−22\frac{n-2}{2}

對。每對需 33 次比較,因此總比較次數為

1+3(n−22)=3n2−2.1+3\left(\frac{n-2}{2}\right) = \frac{3n}{2}-2.

情況二:nn 為奇數且 n>1n>1

令

min⁡=max⁡=A1\min=\max=A_1

不需比較。

剩下 n−1n-1 個元素,共形成

n−12\frac{n-1}{2}

對。每對需 33 次比較,因此總比較次數為

🔒

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

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

免費註冊

第 12 題15 分

There are nn stations along a coastal railway (n>0n > 0). You're planning to select some of them to open cafes. Three arrays SS, LL and RR have been given, including

  • S=(s1,s2,…,sn)S = (s_1, s_2, \dots, s_n): the list of the stations from s1s_1 (first) to sns_n (last).
  • L=(l1,l2,…,ln)L = (l_1, l_2, \dots, l_n): the locations of the stations, where lil_i is the distance of sis_i from the first station s1s_1. So l1=0l_1 = 0 and lnl_n is the length of the railway. l1<l2<⋯<lnl_1 < l_2 < \dots < l_n.
  • R=(r1,r2,…,rn)R = (r_1, r_2, \dots, r_n): the revenues of the cafes, where rir_i (>0> 0) is the revenue for opening a cafe in sis_i.

The only one constraint in your plan is that the distance of any pair of your selected stations should be longer than a given threshold TT. If sis_i and sjs_j (i≠ji \neq j) are selected, the total revenue would be li+ljl_i + l_j. Different selection leads to different total revenue. Given SS, LL, RR and TT, your goal is to pick up a subset of the stations to maximize the total revenue under the constraint. Suppose that f(n)f(n) returns the maximum total revenue for the cafes you select from the first nn stations. Please answer the following questions. No code is required (code will not be graded).

(a) (9 points) Give an O(n2)O(n^2) solution by defining a recurrence formula for f(n)f(n). Clearly explain the meaning of your formula and why it can be computed in O(n2)O(n^2) time.
(b) (6 points) Consider the special case that the distance difference between two consecutive stations is 1, i.e., li+1−li=1l_{i+1} - l_i = 1 (1≤i≤n−11 \le i \le n - 1). Give an O(n)O(n) solution by defining a recurrence formula for f(n)f(n). Clearly explain the meaning of your formula and why it can be computed in O(n)O(n) time.

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

這一題的完整詳解

核心觀念

本題是「排序後的加權間隔選擇」問題:

  • 車站已依位置排序:l1<l2<⋯<lnl_1<l_2<\cdots<l_n。
  • 每個車站 sis_i 有收益 rir_i。
  • 任兩個被選車站的距離必須嚴格大於 TT。
  • 目標是在合法選擇中,使總收益最大。

題幹中「total revenue would be li+ljl_i+l_j」應為筆誤;收益陣列已定義為 R=(r1,…,rn)R=(r_1,\ldots,r_n),以下依正確意義使用總收益 ∑ri\sum r_i。

令

f(i)=只考慮前 i 個車站時,可得到的最大總收益f(i)=\text{只考慮前 }i\text{ 個車站時,可得到的最大總收益}

並設定

f(0)=0。f(0)=0。

由於所有 ri>0r_i>0,選擇一個車站的收益為 rir_i。


(a) O(n2)O(n^2) 解法

對每個車站 sis_i,定義

p(i)=max⁡{j<i∣li−lj>T},p(i)=\max\{j<i\mid l_i-l_j>T\},

若不存在符合條件的 jj,則令 p(i)=0p(i)=0。

p(i)p(i) 表示:在選擇車站 sis_i 時,所有可能與它同時被選的較早車站,都必須位於前 p(i)p(i) 個車站之中。

因此,考慮前 ii 個車站時有兩種情況:

  1. 不選擇 sis_i

    此時收益為

    f(i−1)。f(i-1)。
  2. 選擇 sis_i

    由於任一先前選取的車站必須滿足與 sis_i 的距離大於 TT,先前可選的車站只能來自前 p(i)p(i) 個車站。因此收益為

    ri+f(p(i))。r_i+f(p(i))。

得到遞迴式:

f(i)=max⁡(f(i−1), ri+f(p(i)))\boxed{ f(i)=\max\bigl(f(i-1),\ r_i+f(p(i))\bigr) }

最後答案為 f(n)f(n)。

為何遞迴式正確

任一個最佳解若不包含 sis_i,其收益至多為 f(i−1)f(i-1)。

若最佳解包含 sis_i,則其餘被選車站必須全部位於前 p(i)p(i) 個車站中;否則若存在 sjs_j 且 j>p(i)j>p(i),便有

li−lj≤T,l_i-l_j\le T,

違反距離必須嚴格大於 TT 的限制。因此,其餘車站的最大收益為 f(p(i))f(p(i)),總收益為 ri+f(p(i))r_i+f(p(i))。

兩種情況取最大值即可涵蓋所有合法選擇。

時間複雜度

每個 p(i)p(i) 可以由向前掃描求得,最多檢查 i−1i-1 個車站,因此所有 p(i)p(i) 的計算時間為

O(1+2+⋯+n)=O(n2)。O(1+2+\cdots+n)=O(n^2)。

之後每個 f(i)f(i) 只需 O(1)O(1) 時間計算,所以總時間複雜度為

O(n2)。\boxed{O(n^2)}。

若使用陣列儲存 f(0),f(1),…,f(n)f(0),f(1),\ldots,f(n),空間複雜度為 O(n)O(n)。


(b) 相鄰車站距離皆為 11 時的 O(n)O(n) 解法

現在有

li+1−li=1。l_{i+1}-l_i=1。

因為 l1=0l_1=0,所以

li=i−1。l_i=i-1。

對任意 j<ij<i,

li−lj=(i−1)−(j−1)=i−j。l_i-l_j=(i-1)-(j-1)=i-j。

合法條件為

i−j>T。i-j>T。

由於 i−ji-j 必為整數,最小合法距離為

d=⌊T⌋+1。d=\lfloor T\rfloor+1。

因此,若選擇 sis_i,最晚可以搭配的先前車站索引為

p(i)=i−d。p(i)=i-d。

當 i−d<0i-d<0 時,令 f(i−d)=f(0)=0f(i-d)=f(0)=0。

遞迴式化為:

f(i)=max⁡(f(i−1), ri+f(i−d))\boxed{ f(i)=\max\bigl(f(i-1),\ r_i+f(i-d)\bigr) }

其中

d=⌊T⌋+1。d=\lfloor T\rfloor+1。
🔒

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

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

免費註冊

第 13 題15 分

  1. (15 points) A disjoint-set data structure supports two operations. One is UNION(x, y), which merges the two roots of the trees containing xx and yy. The other is FIND(x), which returns the root of the tree containing xx. Union-by-height is a union heuristic, which keeps track of the heights of the trees to attach the shorter tree to the root of the taller tree.

(a) (9 points) Given an undirected graph G=(V,E)G = (V, E), where V={v1,…,vm}V = \{v_1, \dots, v_m\} (m>0m > 0) and E={e1,…,en}E = \{e_1, \dots, e_n\} (n>0n > 0), devise an algorithm to check if the graph GG is a tree or not by using UNION(v_i, v_j) with union-by-height and FIND(v_k) with no path compression, where vi,vjv_i, v_j and vk∈Vv_k \in V. Clearly describe your solution and analyze the time complexity of your algorithm in the worst case. No code is required (code will not be graded).

(b) (6 points) The union-by-height heuristic prevents the height of a tree from growing linearly. Consider another heuristic, called union-by-descendant, which always attaches the tree with fewer descendants to the root of the tree with more descendants. Suppose that path compression is not applied. Which of the two heuristics is asymptotically better? Why?

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

這一題的完整詳解

核心觀念

無向圖 G=(V,E)G = (V, E) 是一棵樹(tree),當且僅當同時滿足以下兩個條件:

  1. 無環(acyclic):圖中不存在任何 cycle(包括自環與重邊)。
  2. 連通(connected):所有頂點屬於同一個連通元件。

利用 Disjoint-Set 資料結構維護連通元件:每個集合代表一個連通元件,初始時每個頂點各自成一個集合,每加入一條邊就檢查兩端點是否已屬於同一集合(判斷是否成環)並合併不同元件。


(a) 演算法設計與最壞時間複雜度分析

演算法步驟

  1. 初始化:為每個頂點 vi∈Vv_i \in V(i=1,…,mi = 1, \dots, m)建立一個僅包含自己的獨立集合 {vi}\{v_i\},高度設為 00,並令連通元件計數器 components←m\text{components} \leftarrow m。
  2. 逐邊處理:依序讀取每條邊 ek=(vi,vj)∈Ee_k = (v_i, v_j) \in E(k=1,…,nk = 1, \dots, n):
    • 執行 ri=FIND⁡(vi)r_i = \operatorname{FIND}(v_i) 與 rj=FIND⁡(vj)r_j = \operatorname{FIND}(v_j)(不使用 path compression)。
    • 若 ri=rjr_i = r_j,代表 viv_i 與 vjv_j 在加入 eke_k 前已連通,加入 eke_k 必形成 cycle(含自環或重邊),因此立即終止並回傳「GG 不是樹」。
    • 若 ri≠rjr_i \neq r_j,執行 UNION⁡(vi,vj)\operatorname{UNION}(v_i, v_j)(依 union-by-height 將較矮的樹接到較高的樹根下,僅當兩樹等高時新根高度加 11),並將 components\text{components} 減 11。
  3. 連通性檢查:若所有 nn 條邊皆處理完畢且未發現 cycle,檢查 components\text{components} 是否等於 11:
    • 若 components=1\text{components} = 1,回傳「GG 是樹」。
    • 若 components>1\text{components} > 1,代表圖不連通,回傳「GG 不是樹」。

正確性說明

  • 每次成功合併兩個不同集合時,兩端點原本屬於不同連通元件,因此加入該邊不會產生 cycle,且連通元件數嚴格減少 11。
  • 若某條邊的兩端點 FIND 回傳相同根節點,代表兩點間已存在路徑(或為同一頂點的自環),加入此邊必定形成 cycle。
  • 演算法回傳「是樹」若且唯若全程無 cycle(圖為森林)且最終連通元件數為 11(圖連通),完全等價於樹的定義。

最壞時間複雜度分析

  1. 單次操作上界:
    在 union-by-height 下,樹高只有在兩棵高度相同的樹合併時才會增加 11。由數學歸納法可知,高度為 hh 的樹至少包含 2h2^h 個節點。由於總頂點數為 mm,任何集合樹的高度滿足:
    2h≤m  ⟹  h≤⌊log⁡2m⌋=O(log⁡m)2^h \le m \implies h \le \lfloor \log_2 m \rfloor = O(\log m)
    因不使用 path compression,單次 FIND 沿父指標走到根節點,最壞時間為 O(log⁡m)O(\log m);UNION 在已知兩樹根節點(或直接對兩點先做兩次 FIND 再於 O(1)O(1) 時間內合併樹根)下,每次處理一條邊需 O(log⁡m)O(\log m) 時間。

  2. 處理邊數上界:
    演算法在偵測到 cycle 時即提前終止。由於 components\text{components} 初始為 mm,每次無環的合併使 components\text{components} 減 11 且連通元件數至少為 11,因此最多只會成功執行 m−1m - 1 次 UNION;第 mm 條邊(若存在)必定會觸發 ri=rjr_i = r_j 而終止。故迴圈最多只會執行 min⁡(n,m)≤m\min(n, m) \le m 次。

  3. 總時間複雜度:

    • 初始化 mm 個集合:O(m)O(m)。
    • 處理至多 min⁡(n,m)\min(n, m) 條邊:min⁡(n,m)⋅O(log⁡m)=O(mlog⁡m)\min(n, m) \cdot O(\log m) = O(m \log m)。
    • 總最壞時間複雜度為:
      O(m)+O(mlog⁡m)=O(mlog⁡m)O(m) + O(m \log m) = \boxed{O(m \log m)}

🔒

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

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

免費註冊

第 14 題20 分

A tree TT is assumed to be simple, undirected, and with positive edge-weights. Let dT(u,v)d_T(u, v) denote the distance between uu and vv on TT. For a vertex vv, the eccentricity of vv is the maximum of the distance to any vertex in the tree, i.e., max⁡u∈V{dT(v,u)}\max_{u \in V}\{d_T(v, u)\}. The diameter of a tree is the maximum of the eccentricity of any vertex in the tree. (The term "diameter" is overloaded. It is defined as the maximum eccentricity and also as the path of length equal to the maximum eccentricity.) The radius of a tree is the minimum eccentricity among all vertices in the tree, and a center of a tree is a vertex with eccentricity equal to the radius.
(a) (5 points) Prove or disprove that there exists a tree with three different diameters and two centers.
(b) (5 points) Prove or disprove that there exists a tree with three centers.
(c) (10 points) Prove or disprove that any center of a given tree TT must lie in the diameter of TT.

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

這一題的完整詳解

核心性質

設樹 T=(V,E)T=(V,E) 的所有邊權重皆為正數,任兩點 u,vu,v 間的唯一路徑長度記為 dT(u,v)d_T(u,v),頂點 vv 的離心率(eccentricity)為 e(v)=max⁡u∈VdT(v,u)e(v)=\max_{u\in V} d_T(v,u)。若 ∣V∣=1|V|=1,唯一頂點即為中心且位於直徑上,以下討論 ∣V∣≥2|V|\ge 2 之情形。

引理:若 s,ts,t 為 TT 上任一條直徑路徑 PP 的兩個端點,則對任意頂點 v∈Vv\in V,
e(v)=max⁡{dT(v,s), dT(v,t)}.e(v)=\max\{d_T(v,s),\, d_T(v,t)\}.

證明:取任意頂點 u∈Vu\in V,令 qq 為 PP 上距離 uu 最近的頂點(亦即 s,t,us,t,u 三點間路徑的交會點)。設
A=dT(q,s),B=dT(q,t),C=dT(q,u).A=d_T(q,s),\qquad B=d_T(q,t),\qquad C=d_T(q,u).
由於 ss 到 tt 為直徑,路徑長度 A+BA+B 為全樹最大距離,故
A+B≥A+C  ⟹  B≥C,A+B≥B+C  ⟹  A≥C.A+B \ge A+C \implies B\ge C,\qquad A+B \ge B+C \implies A\ge C.
依 vv 相對於 qq 的位置分情況討論:

  1. 若 vv 到 uu 的路徑經過 qq,則 dT(v,u)=dT(v,q)+Cd_T(v,u)=d_T(v,q)+C;此時 vv 到 ss 或 tt 必至少有一條路徑經過 qq(否則 vv 同時在 ss 支線與 tt 支線上,矛盾),故
    max⁡{dT(v,s),dT(v,t)}≥dT(v,q)+min⁡{A,B}≥dT(v,q)+C=dT(v,u).\max\{d_T(v,s),d_T(v,t)\} \ge d_T(v,q)+\min\{A,B\} \ge d_T(v,q)+C = d_T(v,u).
  2. 若 vv 到 uu 的路徑不經過 qq(即 vv 與 uu 位於 qq 的同一側分支),則 vv 到 ss 與 vv 到 tt 的路徑皆必經過 qq,且 dT(v,u)≤dT(v,q)+Cd_T(v,u)\le d_T(v,q)+C,故
    dT(v,s)=dT(v,q)+A≥dT(v,q)+C≥dT(v,u).d_T(v,s)=d_T(v,q)+A \ge d_T(v,q)+C \ge d_T(v,u).

因此對所有 u∈Vu\in V 皆有 max⁡{dT(v,s),dT(v,t)}≥dT(v,u)\max\{d_T(v,s),d_T(v,t)\}\ge d_T(v,u),故 e(v)=max⁡{dT(v,s),dT(v,t)}e(v)=\max\{d_T(v,s),d_T(v,t)\}。


(a) 是否存在具有三條不同直徑且有兩個中心的樹?

存在(True)。構造無向正權重樹 TT 如下:

  • 頂點集 V={a,b,x1,y1,y2,y3}V=\{a,b,x_1,y_1,y_2,y_3\}。
  • 邊與權重:w(a,b)=2w(a,b)=2,w(a,x1)=1w(a,x_1)=1,以及 w(b,y1)=w(b,y2)=w(b,y3)=1w(b,y_1)=w(b,y_2)=w(b,y_3)=1。

計算各點對距離與離心率:

  • 對任一 j∈{1,2,3}j\in\{1,2,3\},dT(x1,yj)=1+2+1=4d_T(x_1,y_j)=1+2+1=4。
  • 任意兩葉節點 yi,yjy_i,y_j(i≠ji\ne j)間的距離為 dT(yi,yj)=1+1=2<4d_T(y_i,y_j)=1+1=2<4;其餘任兩點間距離皆不超過 33。
  • 故樹的直徑長度為 44,且長度為 44 的直徑路徑恰有三條:
    x1−a−b−y1,x1−a−b−y2,x1−a−b−y3.x_1 - a - b - y_1,\qquad x_1 - a - b - y_2,\qquad x_1 - a - b - y_3.
  • 各頂點的離心率分別為:
    e(a)=max⁡{1,3,3,3}=3,e(b)=max⁡{3,1,1,1}=3,e(a)=\max\{1,3,3,3\}=3,\qquad e(b)=\max\{3,1,1,1\}=3,
    e(x1)=4,e(y1)=e(y2)=e(y3)=4.e(x_1)=4,\qquad e(y_1)=e(y_2)=e(y_3)=4.

因此樹的半徑為 33,中心恰為 a,ba,b 兩個頂點,且具有三條不同直徑。


(b) 是否存在具有三個中心的樹?

不存在(False)。正權重樹最多只有兩個中心。

證明:固定任一條直徑路徑 PP,端點為 s,ts,t,長度為 D=dT(s,t)D=d_T(s,t)。

首先,任何不在 PP 上的頂點 v∉Pv\notin P 都不可能是中心。沿著 vv 往 PP 的唯一路徑踏出第一步,設相鄰頂點為 v′v',其邊權重 w(v,v′)=dT(v,v′)>0w(v,v')=d_T(v,v')>0。因為 s,t∈Ps,t\in P,從 vv 到 ss 與 vv 到 tt 的唯一路徑皆必先經過 v′v',所以
dT(v′,s)=dT(v,s)−dT(v,v′),dT(v′,t)=dT(v,t)−dT(v,v′).d_T(v',s)=d_T(v,s)-d_T(v,v'),\qquad d_T(v',t)=d_T(v,t)-d_T(v,v').
由引理可得

🔒

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

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

免費註冊

其他考古題