CE100 Algorithms and Programming II

CE100 Algorithms and Programming II

Week-7 (Greedy Algorithms, Knapsack)

Spring Semester, 2021-2022

Download DOC, SLIDE, PPTX

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Algorithms, Knapsack

Outline

  • Greedy Algorithms and Dynamic Programming Differences
  • Greedy Algorithms
    • Activity Selection Problem
    • Knapsack Problems
      • The 0-1 knapsack problem
      • The fractional knapsack problem
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Activity Selection Problem

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Activity Selection Problem

  • We have:

    • A set of activities with fixed start and finish times
    • One shared resource (only one activity can use at any time)
  • Objective: Choose the max number of compatible activities

  • Note: Objective is to maximize the number of activities, not the total time of activities.

  • Example:

    • Activities: Meetings with fixed start and finish times
    • Shared resource: A meeting room
      • Objective: Schedule the max number of meetings
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Activity Selection Problem

  • Input: a set S={a1,a2,,an}S=\{a_{1}, a_{2}, \dots, a_{n}\} of n activities
  • sis_i : Start time of activity aia_i,
  • fif_i : Finish time of activity aia_i
    Activity ii takes place in [si,fi)[s_i, f_i )
  • Aim: Find max-size subset AA of mutually compatible activities
    • Max number of activities, not max time spent in activities
    • Activities ii and jj are compatible if intervals [si,fi)[s_i, f_i ) and [sj,fj)[s_j, f_j) do not overlap, i.e., either sifjs_i \geq f_j or sjfis_j \geq f_i
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Activity Selection Problem An Example

center

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Optimal Substructure Property

  • Consider an optimal solution AA for activity set SS.
  • Let kk be the activity in AA with the earliest finish time

center

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Optimal Substructure Property

  • Consider an optimal solution AA for activity set SS.
  • Let kk be the activity in AA with the earliest finish time
  • Now, consider the subproblem SkS_k' that has the activities that start after kk finishes, i.e. Sk={aiS:sifk}S_k'=\{a_i \in S: s_i \geq f_k \}
  • What can we say about the optimal solution to SkS_k' ?

center

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Optimal Substructure Property

  • Consider an optimal solution AA for activity set SS.
  • Let kk be the activity in AA with the earliest finish time
  • Now, consider the subproblem SkS_k' that has the activities that start after kk finishes, i.e. Sk={aiS:sifk}S_k'=\{a_i \in S: s_i \geq f_k \}
  • A{k}A-\{k\} is an optimal solution for SkS_k'. Why?

center

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Optimal Substructure

  • Theorem: Let kk be the activity with the earliest finish time in an optimal soln ASA \subseteq S then
    • A{k}A-\{k\} is an optimal solution to subproblem
    • Sk={aiS:sifk}S_k' = \{a_i \in S: s_i \geq f_k \}
  • Proof (by contradiction):
    • \rhd Let BB' be an optimal solution to SkS_k' and
      • B>A{k}=A1|B'| > | A-\{k\}| = | A | - 1
    • Then, B=B{k}B = B' \cup \{k\} is compatible and
      • B=B+1>A|B| = |B'|+1 > | A |
    • Contradiction to the optimality of AA
      Q.E.D.Q.E.D.
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Optimal Substructure

  • Recursive formulation: Choose the first activity kk, and then solve the remaining subproblem SkS_k'

  • How to choose the first activity kk?

    • DP, memoized recursion?
      • i.e. choose the kk value that will have the max size for SkS_k'
  • DP would work,

    • but is it necessary to try all possible values for kk?
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Choice Property

  • Assume (without loss of generality) f1f2fnf_1 \leq f_2 \leq \dots \leq f_n

    • If not, sort activities according to their finish times in non-decreasing order
  • Greedy choice property: a sequence of locally optimal (greedy) choices \Rightarrow an optimal solution

  • How to choose the first activity greedily without losing optimality?

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Choice Property - Theorem

  • Let activity set S={a1,a2,an}S = \{a_1, a_2, \dots a_n\}, where f1f2fnf_1 \leq f_2 \leq \dots \leq f_n

  • Theorem: There exists an optimal solution ASA \subseteq S such that a1Aa_1 \in A

In other words, the activity with the earliest finish time is guaranteed to be in an optimal solution.

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Choice Property - Proof

  • Theorem: There exists an optimal solution ASA \subseteq S such that a1Aa_1 \in A

  • Proof: Consider an arbitrary optimal solution B={ak,a,am,}B = \{a_k, a_{\ell}, a_m, \dots\}, where fk<f<fm<f_k < f_{\ell} < f_m < \dots

    • If k=1k = 1, then BB starts with a1a_1, and the proof is complete
    • If k>1k > 1, then create another solution BB' by replacing aka_k with a1a_1. Since f1fkf_1 \leq f_k, BB' is guaranteed to be valid, and B=B|B'| = |B|, hence also optimal

center

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Algorithm

  • So far, we have:
    • Optimal substructure property: If A={ak,}A = \{a_k, \dots \} is an optimal solution, then A{ak}A-\{a_k\} must be optimal for subproblem SkS_k', where Sk={aiS:sifk}Sk' = \{a_i \in S: s_i \geq f_k\}
      • Note: aka_k is the activity with the earliest finish time in AA
    • Greedy choice property: There is an optimal solution AA that contains a1a_1
      • Note: a1a_1 is the activity with the earliest finish time in SS
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Algorithm

center

explained in the next slide..

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Algorithm

  • Theorem: There exists an optimal solution ASA \subseteq S such that a1Aa_1 \in A

  • Basic idea of the greedy algorithm:

    • Add a1a_1 to AA
    • Solve the remaining subproblem S1S_1', and then append the result to AA
  • Remember arbitary optimal solution explaination from previous sections (finish time order is important for a1a_1 selection with star time and overlapping checking)

    • B={ak,a,am,}B = \{a_k, a_{\ell}, a_m, \dots\},
    • where fk<f<fm<f_k < f_{\ell} < f_m < \dots
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Algorithm for Activity Selection

Definitions in Greedy Algorithm:

  • jj: specifies the index of most recent activity added to AA

  • fj=Max{fk:kA}f_j = Max\{f_k : k \in A\}, max finish time of any activity in AA;

    • because activities are processed in non-decreasing order of finish times
  • Thus, sifjs_i \geq f_j checks the compatibility of ii to current AA

  • Running time: Θ(n)\Theta(n) assuming that the activities were already sorted.

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Algorithm for Activity Selection

Pseudocode for Greedy Algorithm:

GAS(s,f,n) {A{1}j1for i2 to n doif sifj thenAA{i}jiendifendfor}\begin{align*} & \text{GAS}(s, f, n) \ \{ \\ & \quad A \leftarrow \{1\} \\ & \quad j \leftarrow 1 \\ & \quad \text{for} \ i \leftarrow 2 \ \text{to} \ n \ \text{do} \\ & \qquad \text{if} \ s_i \geq f_j \ \text{then} \\ & \qquad \quad A \leftarrow A \cup \{i\} \\ & \qquad \quad j \leftarrow i \\ & \qquad \text{endif} \\ & \quad \text{endfor} \\ & \quad \} \end{align*}

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Algorithm for Activity Selection, An Example (Step-1)

center

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Algorithm for Activity Selection, An Example (Step-2)

center

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Algorithm for Activity Selection, An Example (Step-3)

center

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Algorithm for Activity Selection, An Example (Step-4)

center

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Algorithm for Activity Selection, An Example (Step-5)

center

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Algorithm for Activity Selection, An Example (Step-6)

center

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Algorithm for Activity Selection, An Example (Step-7)

Final Solution

center

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Comparison of DP and Greedy Algorithms

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Reminder: DP-Based Matrix Chain Order

mij=MINik<j{mik+mk+1,j+pi1pkpj}m_{ij}=\underset{i \leq k < j}{MIN} \{ m_{ik} + m_{k+1,j} + p_{i-1} p_k p_j \}

  • We don’t know ahead of time which kk value to choose.

  • We first need to compute the results of subproblems mikm_{ik} and mk+1,jm_{k+1,j} before computing mijm_{ij}

  • The selection of kk is done based on the results of the subproblems.

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Algorithm for Activity Selection

center

explained in the next slide..

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Algorithm for Activity Selection

  • Make a greedy selection in the beginning:
    • Choose a1a_1 (the activity with the earliest finish time)
  • Solve the remaining subproblem S1S_1' (all activities that start after a1)
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy vs Dynamic Programming

  • Optimal substructure property exploited by both Greedy and DP strategies
  • Greedy Choice Property: A sequence of locally optimal choices \Rightarrow an optimal solution
    • We make the choice that seems best at the moment
    • Then solve the subproblem arising after the choice is made
  • DP: We also make a choice/decision at each step, but the choice may depend on the optimal solutions to subproblems
  • Greedy: The choice may depend on the choices made so far, but it cannot depend on any future choices or on the solutions to subproblems
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy vs Dynamic Programming

  • DP is a bottom-up strategy (use memory to store the results of subproblems)
  • Greedy is a top-down strategy (make choices at each step)
    • each greedy choice in the sequence iteratively reduces each problem to a similar but smaller problem
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Proof of Correctness of Greedy Algorithms

  • Examine a globally optimal solution
  • Show that this soln can be modified so that
    • (1) A greedy choice is made as the first step
    • (2) This choice reduces the problem to a similar but smaller problem
  • Apply induction to show that a greedy choice can be used at every step
  • Showing (2) reduces the proof of correctness to proving that the problem exhibits optimal substructure property
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Choice Property - Proof

  • Theorem: There exists an optimal solution ASA \subseteq S such that a1Aa_1 \in A

  • Proof: Consider an arbitrary optimal solution B={ak,a,am,}B = \{a_k, a_{\ell}, a_m, \dots\}, where fk<f<fm<f_k < f_{\ell} < f_m < \dots

    • If k=1k = 1, then BB starts with a1a_1, and the proof is complete
    • If k>1k > 1, then create another solution BB' by replacing aka_k with a1a_1. Since f1fkf_1 \leq f_k, BB' is guaranteed to be valid, and B=B|B'| = |B|, hence also optimal

center

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Elements of Greedy Strategy

  • How can you judge whether

  • A greedy algorithm will solve a particular optimization problem?

  • Two key ingredients

    • Greedy choice property
    • Optimal substructure property
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Key Ingredients of Greedy Strategy

  • Greedy Choice Property: A globally optimal solution can be arrived at by making locally optimal (greedy) choices
  • In DP,we make a choice at each step but the choice may depend on the solutions to subproblems
  • In Greedy Algorithms, we make the choice that seems best at that moment then solve the subproblems arising after the choice is made
    • The choice may depend on choices so far, but it cannot depend on any future choice or on the solutions to subproblems
  • DP solves the problem bottom-up
  • Greedy usually progresses in a top-down fashion by making one greedy choice after another reducing each given problem instance to a smaller one
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Key Ingredients: Greedy Choice Property

  • We must prove that a greedy choice at each step yields a globally optimal solution
  • The proof examines a globally optimal solution
  • Shows that the soln can be modified so that a greedy choice made as the first step reduces the problem to a similar but smaller subproblem
  • Then induction is applied to show that a greedy choice can be used at each step
  • Hence, this induction proof reduces the proof of correctness to demonstrating that an optimal solution must exhibit optimal substructure property
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Key Ingredients: Greedy Choice Property

  • How to prove the greedy choice property?
    • Consider the greedy choice cc
    • Assume that there is an optimal solution BB that doesn’t contain cc.
    • Show that it is possible to convert BB to another optimal solution BB', where BB' contains cc.
  • Example: Activity selection algorithm
    • Greedy choice: a1a_1 (the activity with the earliest finish time)
    • Consider an optimal solution BB without a1a_1
    • Replace the first activity in BB with a1a_1 to construct BB'
    • Prove that BB' must be an optimal solution
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Key Ingredients: Optimal Substructure

  • A problem exhibits optimal substructure if an optimal solution to the problem contains within it optimal solutions to subproblems

  • Example: Activity selection problem SS

    • If an optimal solution A to S begins with activity a1 then the set of activities

    A=A{a1}A' = A - \{a_1\}

    • is an optimal solution to the activity selection problem

    S={aiS:sif1}S' = \{ a_i \in S : s_i \geq f_1 \}

    • where sis_i is the start time of activity aia_i and fif_i is the finish time of activity aia_i
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Key Ingredients: Optimal Substructure

  • Optimal substructure property is exploited by both Greedy and dynamic programming strategies
  • Hence one may
    • Try to generate a dynamic programming soln to a problem when a greedy strategy suffices  inefficient
    • Or, may mistakenly think that a greedy soln works when in fact a DP soln is required  incorrect
  • Example: Knapsack Problems(S, w)
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Knapsack Problems

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Knapsack Problem

  • Each item ii has:

    • weight wiw_i
    • value viv_i
  • A thief has a knapsack of weight capacity ww

  • Which items to choose to maximize the value of the items in the knapsack?

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Knapsack Problem: Two Versions

  • The 0-1 knapsack problem:

    • Each item is discrete.
    • Each item either chosen as a whole or not chosen.
    • Examples: TV, laptop, gold bricks, etc.
  • The fractional knapsack problem:

    • Can choose fractional part of each item.
    • If item i has weight wi, we can choose any amount ≤ wi
    • Examples: Gold dust, silver dust, rice, etc.
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Knapsack Problems

  • The 0-1 Knapsack Problem(S,WS, W)
    • A thief robbing a store finds nn items S={I1,I2,,In}S=\{I_1, I_2, \dots , I_n\}, the ith item is worth viv_i dollars and weighs wiw_i pounds, where vi and wi are integers
    • He wants to take as valuable a load as possible, but he can carry at most WW pounds in his knapsack, where WW is an integer
    • The thief cannot take a fractional amount of an item
  • The Fractional Knapsack Problem (S,WS, W)
    • The scenario is the same
    • But, the thief can take fractions of items rather than having to make binary (010-1) choice for each item
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Optimal Substructure Property for the 0-1 Knapsack Problem (S, W)

  • Consider an optimal load L for the problem (S, W).
  • Let Ij be an item chosen in L with weight wj
  • Assume we remove Ij from L, and let:

Lj=L{Ij}Sj=S{Ij}Wj=Wwj\begin{align*} & L_{j}' = L – \{I_j\} \\ & S_{j}' = S – \{I_j\} \\ & W_{j}' = W – w_j \end{align*}

  • Q: What can we say about the optimal substructure property?

center

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Optimal Substructure Property for the 0-1 Knapsack Problem (S, W)

Lj=L{Ij}Sj=S{Ij}Wj=Wwj\begin{align*} & L_{j}' = L – \{I_j\} \\ & S_{j}' = S – \{I_j\} \\ & W_{j}' = W – w_j \end{align*}

  • Optimal substructure property:
    • LjL_j' must be an optimal solution for (Sj,Wj)(S_j', W_j')
  • Why?
    • If we remove item jj from LL, we can construct a new optimal solution LjL_j' for (Sj,Wj)(S_j', W_j')
    • If LjL_j' is optimal, then LL must be optimal

center

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Optimal Substructure Property for the 0-1 Knapsack Problem (S, W)

Lj=L{Ij}Sj=S{Ij}Wj=Wwj\begin{align*} & L_j' = L – \{I_j\} \\ & S_j' = S – \{I_j\} \\ & W_j' = W – w_j \end{align*}

  • Optimal substructure: LjL_j' must be an optimal solution for (Sj,Wj)(S_j', W_j')

  • Proof: By contradiction, assume there is a solution BjB_j' for (Sj,Wj)(S_j', W_j'), which is better than LjL_j'.

    • We can construct a solution B for the original problem (S,WS, W) as: B=BjʹIjB = Bjʹ ∪ {Ij}.
    • The total value of BB is now higher than LL, which is a contradiction because LL is optimal for (S,W)(S, W).
  • Q.E.D.Q.E.D.

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Optimal Substructure Property for the Fractional Knapsack Problem (S, W)

  • Consider an optimal solution L for (S, W)

  • If we remove a weight 0<wwj0 < w \leq w_j of item jj from optimal load LL and let:

    • The remaining load

    Lj=L{w pounds of Ij}L_j' = L - \{ w \ \text{pounds of} \ I_j \}

    • must be a most valuable load weighing at most

    Wj=WwW_j' = W - w

    • pounds that the thief can take from

    Sj=S{Ij}{wjw pounds of Ij}S_j' = S - \{I_j\} \cup \{ w_j - w \ \text{pounds of} \ I_j \}

  • That is, Lj´ should be an optimal soln to the

Fractional Knapsack Problem(Sj,Wj)\text{Fractional Knapsack Problem}(S_j', W_j')

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Knapsack Problems

  • Two different problems:

    • 0-1 knapsack problem
    • Fractional knapsack problem
  • The problems are similar.

    • Both problems have optimal substructure property.
  • Which algorithm to solve each problem?

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Fractional Knapsack Problem

  • Can we use a greedy algorithm?

  • Greedy choice: Take as much as possible from the item with the largest value per pound vi/wiv_i/w_i

  • Does the greedy choice property hold?

    • Let jj be the item with the largest value per pound vj/wjv_j/w_j
    • Need to prove that there is an optimal load that has as much jj as possible.
    • Proof: Consider an optimal solution L that does not have the maximum amount of item jj. We could replace the items in LL with item jj until LL has maximum amount of jj. LL would still be optimal, because item jj has the highest value per pound.
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Greedy Solution to Fractional Knapsack

  • (1) Compute the value per pound vi/wiv_i/w_i for each item
  • (2) The thief begins by taking, as much as possible, of the item with the greatest value per pound
  • (3) If the supply of that item is exhausted before filling the knapsack, then he takes, as much as possible, of the item with the next greatest value per pound
  • (4) Repeat (2-3) until his knapsack becomes full

Thus, by sorting the items by value per pound the greedy algorithm runs in O(nlgn)O(nlgn) time

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Fractional Knapsack Problem: Example

center

RTEU CE100 Week-7
CE100 Algorithms and Programming II

0-1 Knapsack Problem

  • Can we use the same greedy algorithm?
    • Is there a better solution?

center

RTEU CE100 Week-7
CE100 Algorithms and Programming II

0-1 Knapsack Problem

  • The optimal solution for this problem is:
    • This solution cannot be obtained using the greedy algorithm

center

RTEU CE100 Week-7
CE100 Algorithms and Programming II

0-1 Knapsack Problem

  • When we consider an item IjI_j for inclusion we must compare the solutions to two subproblems
    • Subproblems in which IjI_j is included and excluded
  • The problem formulated in this way gives rise to many
    • overlapping subproblems (a key ingredient of DP)
      • In fact, dynamic programming can be used to solve the 0-1 Knapsack problem
RTEU CE100 Week-7
CE100 Algorithms and Programming II

0-1 Knapsack Problem

  • A thief robbing a store containing nn articles
    • {a1,a2,,an}\{a_1, a_2, \dots, a_n\}
  • The value of ithi_{th} article is viv_i dollars (viv_i is integer)
  • The weight of ithi_{th} article is wiw_i kg (wiw_i is integer)
  • Thief can carry at most WW kg in his knapsack
  • Which articles should he take to maximize the value of his load?
  • Let Kn,W={a1,a2,,an:W}K_{n,W} = \{a_1, a_2, \dots ,a_n:W\} denote 0-1 knapsack problem
  • Consider the solution as a sequence of nn decisions
    • i.e., ithi_{th} decision: whether thief should pick aia_i for optimal load.
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Optimal Substructure Property

  • Notation: Kn,WK_{n,W}:

    • The items to choose from: {a1,,an}\{a_1, \dots , a_n\}
    • The knapsack capacity: WW
  • Consider an optimal load LL for problem Kn,WK_{n,W}

  • Let’s consider two cases:

    • ana_n is in LL
    • ana_n is not in LL
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Optimal Substructure Property

  • Case 1: If anLa_n \in L
    • What can we say about the optimal substructure?
      • L{an}L – \{a_n\} must be optimal for Kn1,WwnK_{n-1,W-wn}
      • Kn1,WwnK_{n-1,W-wn}:
        • The items to choose from {a1,an1}\{a_1, \dots a_{n-1}\}
        • The knapsack capacity: WwnW – wn
  • Case 2: If anLa_n \notin L
    • What can we say about the optimal substructure?
      • LL must be optimal for Kn1,WK_{n-1,W}
        • Kn1,WK_{n-1,W}:
        • The items to choose from {a1,an1}\{a_1, \dots a_{n-1}\}
        • The knapsack capacity: WW
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Optimal Substructure Property

  • In other words, optimal solution to Kn,WK_{n,W} contains an optimal solution to:
    • either: Kn1,WwnK_{n-1,W-wn} (if ana_n is selected)
    • or: Kn1,WK_{n-1, W} (if ana_n is not selected)
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Recursive Formulation

c[i,w]={0 if i=0, or w=0c[i1,w], if wi>wmax{vi+c[i1,wwi],c[i1,w]otherwisec[i,w] = \begin{cases} 0 & \text{ if } i = 0, \ \text{or} \ w = 0 \\ c[i-1,w], & \text{ if } w_i > w \\ max\{v_i + c[i-1,w-w_i],c[i-1,w] & otherwise \\ \end{cases}

RTEU CE100 Week-7
CE100 Algorithms and Programming II

0-1 Knapsack Problem

  • Recursive definition for value of optimal soln:
    • This recurrence says that an optimal solution Si,wS_{i,w} for Ki,wK_{i,w}
      • either contains aic(Si,w)=vi+c(Si1,wwi)a_i \Rightarrow c(S_i,w) = v_i + c(S_{i-1,w-w_i})
      • or does not contain aic(Si,w)=c(Si1,w)a_i \Rightarrow c(Si,w) = c(S_{i-1},w)
    • If thief decides to pick aia_i
      • He takes viv_i value and he can choose from {a1,a2,,ai1}\{a_1, a_2, \dots,a_{i-1}\} up to the weight limit wwiw - w_i to get c[i1,wwi]c[i-1,w-w_i]
    • If he decides not to pick aia_i
      • He can choose from {a1,a2,,ai1}\{a_1, a_2, \dots ,a_{i-1}\} up to the weight limit ww to get c[i1,w]c[i-1,w]
    • The better of these two choices should be made
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Bottom-up Computation

  • Need to process:
    • c[i,w]c[i, w]
  • after computing:
    • c[i1,w]c[i-1, w],
    • c[i1,wwi]c[i-1, w-w_i]
      • for all wi<ww_i < w
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Bottom-up Computation

for i1 to n dofor w1 to W doc[i,w]\begin{align*} & \quad \text{for} \ i \leftarrow 1 \ \text{to} \ n \ \text{do} \\ & \qquad \text{for} \ w \leftarrow 1 \ \text{to} \ W \ \text{do} \\ & \qquad \quad \dots \\ & \qquad \quad c[i,w] \leftarrow \dots \\ & \qquad \quad \dots \\ \end{align*}

RTEU CE100 Week-7
CE100 Algorithms and Programming II

DP Solution to 0-1 Knapsack

  • cc is an (n+1)×(W+1)(n + 1)\times(W+1) array; c[0n:0W]c[0 \dots n : 0 \dots W]

  • Note : table is computed in row-major order

  • Run time: T(n)=Θ(nW)T(n) = \Theta(nW)

RTEU CE100 Week-7
CE100 Algorithms and Programming II

DP Solution to 0-1 Knapsack

KNAP0-1(v,w,n,W)for ω0 to W doc[0,ω]0for i0 to m doc[i,0]0for i0 to m dofor ω1 to W doif wiω thenc[i,ω]max{vi+c[i1,ωwi],c[i1,ω]}elsec[i,ω]c[i1,ω]return c[m,W]\begin{align*} & \text{KNAP0-1}(v, w, n,W) \\ & \quad \text{for} \ \omega \leftarrow 0 \ \text{to} \ W \ \text{do} \\ & \qquad c[0, \omega] \leftarrow 0 \\ & \quad \text{for} \ i \leftarrow 0 \ \text{to} \ m \ \text{do} \\ & \qquad c[i, 0] \leftarrow 0 \\ & \quad \text{for} \ i \leftarrow 0 \ \text{to} \ m \ \text{do} \\ & \qquad \quad \text{for} \ \omega \leftarrow 1 \ \text{to} \ W \ \text{do} \\ & \qquad \qquad \text{if} \ w_i \leq \omega \ \text{then} \\ & \qquad \qquad \quad c[i, \omega] \leftarrow max\{v_i + c[i-1, \omega - w_i] , c[i -1, \omega]\} \\ & \qquad \qquad \text{else} \\ & \qquad \qquad \quad c[i, \omega] \leftarrow c[i-1, \omega] \\ & \quad return \ c[m,W] \end{align*}

RTEU CE100 Week-7
CE100 Algorithms and Programming II

Constructing an Optimal Solution

  • No extra data structure is maintained to keep track of the choices made to compute c[i,w]c[i, w]
    • i.e. The choice of whether choosing item i or not
  • Possible to understand the choice done by comparing c[i,w]c[i, w] with c[i1,w]c[i-1, w]
    • If c[i,w]=c[i1,w]c[i,w] = c[i-1, w] then it means item i was assumed to be not chosen for the best c[i,w]c[i, w]
RTEU CE100 Week-7
CE100 Algorithms and Programming II

Finding the Set S of Articles in an Optimal Load

SOLKNAP0-1(a,v,w,n,W,c)in;ωWSwhile i0 doif c[i,ω]=c[i1,ω] thenii1elseSS{ai}ωωwiii1return S\begin{align*} & \text{SOLKNAP0-1}(a, v, w, n,W,c) \\ & \quad i \leftarrow n ; \omega \leftarrow W \\ & \quad S \leftarrow \emptyset \\ & \quad while \ i \leftarrow 0 \ do \\ & \qquad if \ c[i, \omega] = c[i-1, \omega] \ then \\ & \qquad \quad i \leftarrow i - 1 \\ & \qquad else \\ & \qquad \quad S \leftarrow S \cup \{a_i\} \\ & \qquad \quad \omega \leftarrow \omega - w_i \\ & \qquad \quad i \leftarrow i - 1 \\ & \quad return \ S \end{align*}

RTEU CE100 Week-7
CE100 Algorithms and Programming II

References

RTEU CE100 Week-7
CE100 Algorithms and Programming II

EndOfWeek7CourseModule-End-Of-Week-7-Course-Module-

RTEU CE100 Week-7