109 年 國立政治大學資訊科學系碩士班《資料結構與演算法》
第 1 題20 分
(20 points) What are the worst case time complexities of the following algorithms?
1.1 Binary search in a sorted array consisting of integers
1.2 Building a binary heap from an unsorted array consisting of integers
1.3 Randomized quicksort for an array consisting of integers
1.4 Kruskal algorithm with disjoint-set-forest for finding the minimum spanning tree given a connected, undirected graph with vertices and edges
登入後即可作答並保存紀錄。
核心觀念
本題考查四種經典演算法的「最壞情況時間複雜度」:
- Binary search:每次比較都將搜尋範圍縮小為原來的一半。
- Binary heap 建構:使用 bottom-up heap construction 時,不是對每個元素個別插入。
- Randomized quicksort:隨機化只能改善平均情況,無法排除最壞情況。
- Kruskal algorithm:總時間主要由邊排序與 disjoint-set 操作決定。
1.1 排序陣列上的 Binary search
解題方法
Binary search 每次選取中間元素與目標值比較:
- 若目標值等於中間元素,搜尋結束。
- 若目標值較小,只搜尋左半部。
- 若目標值較大,只搜尋右半部。
每次搜尋後,候選範圍約縮小為一半,因此可建立遞迴式:
展開 次後,問題規模變為:
當範圍縮小至 時:
每層只進行常數次比較,因此:
最壞情況發生在目標值不存在,或目標值位於最後一次才被找到的位置。
1.2 從未排序陣列建構 Binary heap
核心觀念
若使用 bottom-up heap construction,也稱為 Floyd’s heap construction,會從最後一個非葉節點開始,依序向前執行 sift-down。
高度為 的節點,其 sift-down 最多需要 時間。雖然根節點可能需要 時間,但高高度節點數量很少。
解題方法
將所有節點依高度分類:
- 高度為 的節點約有 個,每個成本為 。
- 高度為 的節點約有 個,每個成本為 。
- 高度為 的節點約有 個,每個成本為 。
- 依此類推。
總成本可表示為:
由於級數
收斂為常數,因此:
所以,從未排序陣列以 bottom-up 方法建構 binary heap 的最壞情況時間複雜度為:
常見陷阱
若逐一將 個元素插入空 heap,每次插入成本最壞為 ,總成本為:
但題目問的是「從未排序陣列建構 heap」,通常採用 bottom-up 方法,因此答案是 。
1.3 Randomized quicksort
核心觀念
Randomized quicksort 隨機選擇 pivot。隨機化能使平均分割較平衡,因此期望時間複雜度為:
但最壞情況仍可能發生。隨機選出的 pivot 可能在每一層都是目前陣列中的最小值或最大值,使分割結果為:
解題方法
在最壞情況下,遞迴式為:
其中 是 partition 的成本。
展開:
因此:
所以 Randomized quicksort 的最壞情況時間複雜度為:
解題技巧
必須區分:
- 最壞情況:
- 期望時間:
- 額外空間:
- 平衡遞迴時約為 。
- 最壞遞迴深度為 。
題目問的是 worst case,因此不能回答 。
1.4 使用 Disjoint-set forest 的 Kruskal algorithm
核心觀念
Kruskal algorithm 的主要步驟如下:
- 將所有邊依權重遞增排序。
- 依序檢查每條邊。
- 若邊的兩端點目前屬於不同集合,便加入 minimum spanning tree,並合併兩個集合。
Disjoint-set forest 通常搭配:
第 2 題20 分
(20 points) Design a dynamic array that supports the following four operations in amortized time. Show your algorithm for each of the four operations in C or pseudo code.
2.1 Initializing an empty array
2.2 Inserting a new element at the end of the array
2.3 Removing the last element of the array
2.4 Access to the kth element of the array
登入後即可作答並保存紀錄。
核心觀念
動態陣列使用一段連續記憶體儲存元素,維護兩個欄位:
size:目前元素數量。capacity:目前已配置的儲存容量。
陣列元素存放於 data[0] 到 data[size - 1]。
當陣列已滿時,配置一段容量加倍的新陣列,複製原有元素後再插入新元素。雖然單次擴充需要 時間,但連續執行 次插入時,總複製次數為
因此插入的攤銷時間為 。
解題方法
假設元素型別為 int,初始容量設定為 $1`。陣列採用「容量不足時加倍」的策略。
2.1 Initializing an empty array
typedef struct {
int *data;
int size;
int capacity;
} DynamicArray;
DynamicArray *initArray() {
DynamicArray *a = malloc(sizeof(DynamicArray));
a->capacity = 1;
a->size = 0;
a->data = malloc(a->capacity * sizeof(int));
return a;
}
初始化後:
只配置固定大小的初始空間,因此時間複雜度為:
空間複雜度為:
2.2 Inserting a new element at the end
void pushBack(DynamicArray *a, int value) {
if (a->size == a->capacity) {
int newCapacity = 2 * a->capacity;
int *newData = malloc(newCapacity * sizeof(int));
for (int i = 0; i < a->size; i++) {
newData[i] = a->data[i];
}
free(a->data);
a->data = newData;
a->capacity = newCapacity;
}
a->data[a->size] = value;
a->size++;
}
當陣列尚未滿時,只需將元素放在 data[size]:
當陣列已滿時,需複製 個元素:
但容量每次加倍,因此執行 次插入所需的總複製成本為:
再加上每次插入本身的 成本,總時間為 ,所以單次插入的攤銷時間為:
最壞單次時間為 ,攤銷時間為 。
2.3 Removing the last element
int popBack(DynamicArray *a) {
if (a->size == 0) {
return ERROR;
}
int value = a->data[a->size - 1];
a->size--;
return value;
}
移除最後一個元素只需將 size 減一,不必搬移其他元素:
此策略保留已配置的容量,因此連續移除元素不會因重新配置記憶體而增加成本。
若需要回收過多的閒置空間,可在
時將容量縮半。搭配「容量不足時加倍」與「使用量低於四分之一時縮半」,仍可使插入與刪除的攤銷時間維持 ;本題不要求回收空間,直接保留容量即可。
2.4 Access to the kth element
若題目中的 $k
第 3 題20 分
(20 points) Given two binary trees, design an algorithm for checking if they are identical in terms of both the structure and the values. The node in the binary tree is defined as follows. Implement the “equal" function in C or pseudo code.
struct node {
int value;
struct node *left, *right;
};
bool equal(struct node *tree1, struct node *tree2)
{
}
登入後即可作答並保存紀錄。
核心觀念
兩棵二元樹「完全相同」必須同時滿足:
- 對應位置的節點結構相同。
- 對應位置的節點值相同。
對任意兩個對應節點 tree1 與 tree2,可依下列遞迴定義判斷:
- 兩者皆為
NULL:代表此位置結構相同。 - 僅有一者為
NULL:代表結構不同。 - 兩者皆存在但
value不同:代表內容不同。 - 兩者皆存在且值相同:必須繼續比較左子樹與右子樹。
因此,兩棵樹相同的條件為:
此定義的前提是兩個根節點都存在。
解題方法
採用遞迴搭配前序走訪的方式,從根節點開始同步比較兩棵樹。
每次呼叫 equal(tree1, tree2) 時,依序處理:
- 若
tree1與tree2都是NULL,回傳true。 - 若只有一個是
NULL,回傳false。 - 若兩個節點的值不同,回傳
false。 - 遞迴比較兩個左子樹及兩個右子樹,兩者都相同才回傳
true。
C 程式碼
#include <stdbool.h>
struct node {
int value;
struct node *left;
struct node *right;
};
bool equal(struct node *tree1, struct node *tree2)
{
/* 兩個位置皆為空,結構相同 */
if (tree1 == NULL && tree2 == NULL) {
return true;
}
/* 僅有一個位置為空,結構不同 */
if (tree1 == NULL || tree2 == NULL) {
return false;
}
/* 對應節點的值不同 */
if (tree1->value != tree2->value) {
return false;
}
/* 左右子樹都相同,整棵樹才相同 */
return equal(tree1->left, tree2->left) &&
equal(tree1->right, tree2->right);
}
正確性說明
以任意兩個對應位置的子樹為對象:
- 若兩個節點皆為空,兩個子樹在此位置都沒有節點,因此結構相同。
- 若只有一個節點為空,另一個位置存在節點,因此結構必定不同。
- 若兩個節點皆存在但值不同,則兩棵樹的節點內容不同。
第 4 題20 分
(20 points) Given an matrix of real numbers, find a maximum sum submatrix of . The maximum sum submatrix of is a submatrix of with the largest sum. Describe your algorithm in C or pseudo code and show its time complexity.
登入後即可作答並保存紀錄。
核心觀念
本題要求在 矩陣中,找出一個「連續矩形子矩陣」,使其中所有元素總和最大。子矩陣必須由連續的列與連續的欄所構成。
核心技巧是將二維問題降成多次一維最大子陣列問題:
- 固定子矩陣的上界與下界。
- 將上下界之間每一欄的元素加總,形成一維陣列。
- 在此一維陣列中找最大連續子陣列,即可決定子矩陣的左界與右界。
一維最大連續子陣列問題可用 Kadane’s algorithm 在 時間內完成。
解題方法
1. 固定上界與下界
假設子矩陣的上界為第 列,下界為第 列,其中
對每一欄 ,計算第 列到第 列的總和:
此時,若選擇連續欄位 到 ,其對應子矩陣的總和為:
因此,固定 與 後,原問題就轉化為:
在一維陣列
colSum中,尋找總和最大的連續區段。
這正是一維最大子陣列問題。
2. 使用 Kadane’s algorithm 找最佳欄範圍
對於一維陣列 colSum,定義:
currentSum:以目前欄位作為右端點時,仍值得延伸的最佳連續區段總和。bestSum:目前看過的所有連續區段中的最大總和。
遞迴關係為:
意義如下:
- 若前一段的
currentSum加上colSum[j]更好,就延續前一段。 - 若直接從第 欄重新開始更好,就捨棄前面的區段。
為了處理矩陣中所有元素皆為負數的情況,不能將初始答案固定為 ,必須將答案初始化為負無限大,並允許選取只包含一個元素的子矩陣。
演算法流程
對每一個可能的上界 top:
- 將
colSum[0..n-1]全部設為 。 - 逐步增加下界
bottom。 - 將第
bottom列加入colSum: - 對目前的
colSum執行 Kadane’s algorithm。 - 若得到更大的總和,更新最佳子矩陣的上下左右界。
關鍵偽程式碼
function MaxSumSubmatrix(M, m, n):
bestSum = -infinity
bestTop = 0
bestBottom = 0
bestLeft = 0
bestRight = 0
for top = 0 to m - 1:
colSum[0..n-1] = 0
for bottom = top to m - 1:
for j = 0 to n - 1:
colSum[j] = colSum[j] + M[bottom][j]
currentSum = colSum[0]
currentLeft = 0
if currentSum > bestSum:
bestSum = currentSum
bestTop = top
bestBottom = bottom
bestLeft = 0
bestRight = 0
for j = 1 to n - 1:
if currentSum + colSum[j] < colSum[j]:
currentSum = colSum[j]
currentLeft = j
else:
currentSum = currentSum + colSum[j]
if currentSum > bestSum:
bestSum = currentSum
bestTop = top
bestBottom = bottom
bestLeft = currentLeft
bestRight = j
return bestSum,
bestTop, bestBottom,
bestLeft, bestRight
回傳的子矩陣為:
其最大總和為 bestSum。
正確性說明
固定任意一組 與 後,每一欄的加總值為:
任意連續欄位 到 所形成的子矩陣總和為:
第 5 題20 分
(20 points) Given a string consisting of characters and a dictionary consisting of words, provide an algorithm for checking if is completely composed of the words in . That is, can be segmented into fragments, and all the fragments are listed in . Describe your algorithm in C or pseudo code and show its time complexity.
登入後即可作答並保存紀錄。
解法概述
利用動態規劃判斷前 個字元是否可由字典 完全組成。設
初始化 ,其餘 。對每個位置 (),檢查所有字典單詞 ,若 且 且 ,則設 ,並可提前跳出內層迴圈。
最後答案為 。
偽代碼
function canSegment(s, D):
n ← length(s)
dp ← array[0..n] of false
dp[0] ← true
for i ← 1 to n:
for each w in D:
l ← length(w)
if l ≤ i and dp[i-l] = true:
if s.substring(i-l, i) = w:
dp[i] ← true
break // 找到可行分割即可
return dp[n]
若欲加速,可先建立以單詞長度分組的哈希表,或使用 Trie,使內層檢查僅遍歷 前的最多 個字元( 為字典中最長單詞長度),時間仍保持 。
時間與空間複雜度
- 時間: