2.8.9 - Optimal Binary Search Tree

1. 介紹

給予n個內部節點加權值 pip_{i} 、n+1個外部節點加權值 qiq_{i} ,在 1n+1(2nn)\frac{1}{n+1}{2n \choose n} 個不同的Binary Search Trees中,具有最小的搜尋總成本的稱為最佳化二元搜尋樹(Optimal Binary Search Tree);可能大於一棵。

搜尋總成本=成功搜尋成本+失敗搜尋成本搜尋總成本=成功搜尋成本+失敗搜尋成本

成功搜尋成本=i=1n(內部節ilevel)pi成功搜尋成本=\sum_{i=1}^{n}(內部節點_{i}的level值)*p_{i}

失敗搜尋成本=j=0n(外部節ilevel)qi失敗搜尋成本=\sum_{j=0}^{n}(外部節點_{i}的level值)*q_{i}

其中,level值即是比較次數。

2. 使用Dynamic Programing解OBST

內部節點: ai+1, ai+2, ...,aja_{i+1},\ a_{i+2},\ ..., a_{j}ai+1<ai+2<...<aja_{i+1}<a_{i+2}<...<a_{j}

內部節點加權值: pi+1, pi+2, ...,pjp_{i+1},\ p_{i+2},\ ..., p_{j}

外部節點加權值: qi, qi+1, ...,qjq_{i},\ q_{i+1},\ ..., q_{j}

Ti,jT_{i,j}: 由 ai+1, ai+2, ...,aja_{i+1},\ a_{i+2},\ ...,a_{j}所組成的OBST

Ci,jC_{i,j}: 表示Ti,jT_{i,j}的總成本

Ri,jR_{i,j}: 表示Ti,jT_{i,j}的Root

Wi,jW_{i,j}: 表示Ti,jT_{i,j}的內、外部節點加權值總和

Ti,iT_{i,i}代表空樹,Ci,j=0C_{i,j}=0Ri,jR_{i,j}NULLWi,j=qiW_{i,j}=q_{i}

從內部節點中ai+1, ai+2, ...,aja_{i+1},\ a_{i+2},\ ..., a_{j},挑選出一個節點 aka_{k} 作為Root,則其左子樹有ai+1, ...,ak1a_{i+1},\ ..., a_{k-1},最佳二元搜尋數樹為 Ti, k1T_{i,\ k-1} ;右子樹有ak+1, ...,aja_{k+1},\ ..., a_{j},最佳二元搜尋數樹為 Tk+1, jT_{k+1,\ j}

Ci,j=pk+(Ci, k1+Wi, k1)+(Ck, j+Wk+1, j)       =Wi,j+Ci,k1+Ck,jC_{i,j}=p_{k}+(C_{i,\ k-1}+W_{i,\ k-1})+(C_{k,\ j}+W_{k+1,\ j})\\\ \ \ \ \ \ \ =W_{i,j}+C_{i,k-1}+C_{k,j}

min{Ci,j}=Wi,j+mini+1kj{Ci,k1+Ck,j}min\{C_{i, j}\}=W_{i,j}+\min_{i+1≤k≤j}\{C_{i,k-1}+C_{k,j}\}

3. 範例

4個內部節點: a1, a2, a3, a4a_{1},\ a_{2},\ a_{3},\ a_{4}a1<a2<a3<a4a_{1}<a_{2}<a_{3}<a_{4}

內部節點加權值: (p1, p2, p3, p4)=(3,3,1,1)(p_{1},\ p_{2},\ p_{3},\ p_{4})=(3,3,1,1)

外部節點加權值: q0, q1, q2, q3, q4=(2,3,1,1,1)q_{0},\ q_{1},\ q_{2},\ q_{3},\ q_{4}=(2,3,1,1,1)

  • 空樹(外部節點是2, 3, 1, 1, 1以此類推)

W0,0=2W_{0,0}=2

W1,1=3W_{1,1}=3

W2,2=1W_{2,2}=1

W3,3=1W_{3,3}=1

W4,4=1W_{4,4}=1

C0,0=0C_{0,0}=0

C1,1=0C_{1,1}=0

C2,2=0C_{2,2}=0

C3,3=0C_{3,3}=0

C4,4=0C_{4,4}=0

R0,0=0R_{0,0}=0

R1,1=0R_{1,1}=0

R2,2=0R_{2,2}=0

R3,3=0R_{3,3}=0

R4,4=0R_{4,4}=0

  • 1個內部節點+2個外部節點

R0,1=1W0,1=a1+q0+q1=3+2+2=8C0,1=8R_{0,1}=1,W_{0,1}=a_{1}+q_{0}+q_{1}=3+2+2=8,C_{0,1}=8

R1,2=2W1,2=a2+q1+q2=3+3+1=7C1,2=7R_{1,2}=2,W_{1,2}=a_{2}+q_{1}+q_{2}=3+3+1=7,C_{1,2}=7

R2,3=3W2,3=a3+q2+q3=1+1+1=3C2,3=3R_{2,3}=3,W_{2,3}=a_{3}+q_{2}+q_{3}=1+1+1=3,C_{2,3}=3

R3,4=4W3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