for k <- 0 to w c[0, k] <- 0 for i <- 1 to n { c[i, 0] <- 0 for k <- 1 to w { if k < w_i c[i, k] <- c[i-1, k] else c[i, k] <- max(c[i-1, k], c[i-1, k-w_i]+v_i) } }
Time complexity
Θ(nW)Pseudo-polynominal
Space complexity
Θ(nW)
Branch and bound 解 0-1 Knapsack problem
對於一個 NP-Completed 問題來說,可以使用「Branch and bound」來解決
「Branch and bound」演算法中,「Bounding function」的設計會是影響整體效能最大的關鍵 ( 收斂快慢 )。
Time complexity:O( 葉節點個數 )
葉節點個數取決問題本身。
組合性問題:2n
排列性問題:n!
將球最佳解的過程視為在一個「State space tree」中尋找最好的節點。
實務上,通常是設計一 個「Bounding function」以估計目前狀態可到最佳解的可能性。
建構「State space tree」時,每次都先展開「Bounding function」的節點。( Branch )
在每次展開的過程中,都可以得到一個目前最佳解 (葉節點),接著,之後不展開「Bounding function 值≤目前最佳解」的內部節點。( Bound )
for j <- 0 to n c[0, j] <- 0 for i <- 0 to m c[i, 0] <- 0 for i <- 1 to m for j <- 1 to n { if(X[i] = Y[i]) c[i, j] = c[i-1, j-1] + 1 else c[i, j] = max(c[i-1, j], c[i, j-1]) }
for i <- 1 to n (「Matrix chain」長度為一) m[i, i] <- 0 for l <- 2 to n (「Matrix chain」長度為二以上) for i <- 1 to n-l+1 (起點) { j <- i+l-1 (終點) m[i, j] <- infinity for k <- i to j-1 { tmp <- m[i, k] + m[k+1, j] + P_i-1 * P_k * P_j if tmp < m[i, j] m[i, j] <- tmp (純量乘法數) s[i, j] <- k (切點) } }
Time complexity
Θ(n3):∑nl=2∑n−l+1i=1∑i+l−2k=i1
Space complexity
Θ(n2)
Ex
A1:3×3
A2:3×7
A3:7×2
A4:2×9
A5:9×4
算出 A1×A2×…×A5 最少的乘法數。
matrixchaindpmartixchainproblem_2
m (乘法數)
1
2
3
4
5
1
0
63(←)
60(←)
114(↓)
156(↓)
2
0
42(←)
96(↓)
138(↓)
3
0
126(←)
128(←)
4
0
72(←)
5
0
s (切點)
2
3
4
5
1
1
1
3
3
2
2
3
3
3
3
3
4
4
最少乘法數:156
最佳乘法順序:(A1×(A2×A3))×(A4×A5)
補充例題
Example(107交通大學資料結構與演算法)
We define the maximum subarray of an array A to be the nonempty, contiguous subarray of A whose value have the largest sum
Fill in the blank (a), (b) in the following c++ function so that it returns value are placed in A[1], A[2], …, A[n-1]
1 2 3 4 5 6 7 8 9 10 11 12 13
intmaxSubarray(int A[], int n){ for(int i = 1; i<n; ++i) { A[i] += A[i-1]; } int ans = A[0]; int k = 0; for(int i = 0; i<n; ++i) { ans = max(ans, (a) ); k = min(k, (b) ); } return ans; }