演算法›Ch1 Introduction第 3 題/共 4 題
3. 隨機演算法、期望值分析、遞迴
#AL-01-003中隨機演算法期望值分析遞迴
Consider the following randomized recursive algorithm, which prints out some number of exclamation marks (!) and some number of asterisks (*). Assume that the size of is initially. What are the expected numbers of !'s and *'s that the algorithm prints out. Choose the tightest possible answers.
RandomizedPrint(A): n = length(A) if n <= 1: print "!" return for i in {0,...,n-1}: print "*" Choose a uniformly random integer p in {1,...,n-1} RandomizedPrint(A[:p]) RandomizedPrint(A[p:])
參考答案與解析
答案 (C):遞迴每次把陣列切成兩段(大小分別為 p 與 n-p,p 在 {1,...,n-1} 均勻隨機),直到剩 1 個元素才印 "!"。因為切割永遠把長度分完,遞迴樹恰有 n 個葉節點,所以 !'s 恰為 Θ(n)(期望值也是 Θ(n))。而每個內部呼叫要印 n 個 *,這與亂數樞紐 quicksort 的遞迴式 T(n)=n+平均(T(p)+T(n-p)) 完全相同,期望值為 Θ(n log n)。
📄 台大114
▤完整推導請見《WH 資工筆記 · 演算法》Ch1 Introduction