演算法›Ch3 動態規劃
第 19 題/共 40 題
◀ AL 19/40
19. Knapsack、Dynamic Programming、Greedy Algorithm
#AL-03-019中KnapsackDynamic ProgrammingGreedy Algorithm
  1. Consider the Knapsack problem with n items and a knapsack size W. Let (a1,b1),(a2,b2),…,(an,bn)(a_1,b_1), (a_2,b_2), \ldots, (a_n,b_n) be the size and profit of the items in order, i.e., aia_i is the size of the ithi^{th} item and bib_i is its profit.

(a) (2%). Consider the following simple greedy algorithm.

  • C←∅C \leftarrow \emptyset, S←{1,2,…,n}S \leftarrow \{1,2,\ldots,n\}.
  • Repeat until S=∅S = \emptyset, do
    • Find i∈Si \in S with the maximum profit-cost ratio. That is, biai=max⁡j∈Sbjaj\frac{b_i}{a_i} = \max_{j \in S} \frac{b_j}{a_j}.
    • Add i to C if ai+size(C)≤Wa_i + size(C) \le W.
    • Remove i from S.

Does this algorithm correctly compute an optimal solution for the Knapsack problem? If so, briefly justify its correctness. If not, provide a counter-example with the smallest number of items.

(b) (2%). For any i and w with 0≤i≤n0 \le i \le n and w≥0w \ge 0, define A(i,w)A(i,w) to be the maximum profit we can obtain, if we are using only the first i items and the knapsack size is w. Consider the following recurrence formula for A(i,w)A(i,w).

A(i,w)={−∞,if w<0,0,if w≥0,i=0,max⁡(A(i−1,w), A(i−1,w−ai)+bi),if w≥0,i>0.A(i,w) = \begin{cases} -\infty, & \text{if } w < 0, \\ 0, & \text{if } w \ge 0, i = 0, \\ \max(A(i-1,w),\ A(i-1,w-a_i)+b_i), & \text{if } w \ge 0, i > 0. \end{cases}

Suppose that W = 5 and we have 3 items with size and profit (4,20), (2,8), (3,14). Use the recurrence to calculate the value A(i,w)A(i,w) for all 0≤i≤30 \le i \le 3 and 0≤w≤50 \le w \le 5 in a table, as shown below. What is the optimal profit?

i\w012345
i=0
i=1
i=2
i=3
📄 交大112
跳轉到第題
▤完整推導請見《WH 資工筆記 · 演算法》Ch3 動態規劃
本章題號 · 1–20 / 40