Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

10/08/2021

Part 1: Naïve to Dynamic 
4.7 Dynamic Programming & Programming
Minimax Algorithm & Proofs Solution Example

Online Lesson 10/8 
Virtual School Victoria

VSV 2021 VCE Algorithmics HESS Unit 4 VSV 2021 VCE Algorithmics HESS Unit 4

Resource Cutting Problem
Resource Cutting Problem
Given: Optimization problem: Cuts n=4 Price
• A resource of a certain length, 𝑛. There are many combinations 
• An array of prices for resource of  1,1,1,1 5
or ways to cut the resource, 
sizes between 1 and 𝑛. 1,1,2 7
What is the best way to cut the 
you want the one that  1,3 9
resource so that you make the most  maximizes the price overall. 2,2 10
money out of selling it? 4 9
Length  i 1 2 3 4
Optimization problem:
• There are many ways to cut the  Price pi 1 5 8 9
resource, you want the best one.

VSV 2021 VCE Algorithmics HESS Unit 4 VSV 2021 VCE Algorithmics HESS Unit 4

Resource Cutting Problem Resource Cutting Problem
• Recursive solution, a brute force approach.
Length  i 1 2 3 4 – Try cutting a first piece of all possible sizes and make a recursive 
Cuts n=4 Price call for cutting the remaining piece
Price pi 1 5 8 9
– Decrease & Conquer recursion
1,1,1,1 4 – Add the values (of the first piece and the result of the recursive call)
– Return the max of all these combinations
1 4 1,1,2 7 • Exponential growth of options to check – with overlapping 
2 3 sub problems.
1 1,3 9
2 3 1 2 1
2,2 10
1 2 1 1
4 9
1
Length  i 1 2 3 4
Price pi 1 5 8 9
Recursion tree n=4

VSV 2021 VCE Algorithmics HESS Unit 4 VSV 2021 VCE Algorithmics HESS Unit 4

1
10/08/2021

Recursion tree n=5
Length  i 1 2 3 4
Price pi 1 5 8 9 Recursive Solution – Naïve Brute Force
set globaltally to –infinity (global)
Function CutResource(p,l,n)
// Input p an array of prices
// Input l an array of lengths ascending
// Input n size to cut
Recursion tree n=6
If (n ≤ 0) then
// base case
return 0
Else
for i=1 to length(l) do
if  n l i 0 then
tally := p[i]+CutResource(p,l,n‐l[i])
Recursion tree n=7 globalTally=max(globalTally, tally)
end if
end do
End If Length  i 1 2 3 4
return tally
Price pi 1 5 8 9
End Function

VSV 2021 VCE Algorithmics HESS Unit 4 VSV 2021 VCE Algorithmics HESS Unit 4

Recursive Solution – Naïve Brute Force Resource Cutting Problem


Recursive solution a brute force 
approach:
– Exponential growth of options 
to check for final solution with 
overlapping sub‐problems.

ATTENTION: Overlapping sub‐problems are observed 
in naïve solution, this is a candidate for Dynamic 
Programming to improve time complexity for finding 
the solution.
Length  i 1 2 3 4
Price pi 1 5 8 9
VSV 2021 VCE Algorithmics HESS Unit 4 VSV 2021 VCE Algorithmics HESS Unit 4

Dynamic Programming Design Pattern Bottom‐Up Dynamic Programming
Function DP‐CutResource(p,l,n) Length  i 1 2 3 4
// Input p an array of prices Price pi 1 5 8 9
Solve for n // Input l an array of lengths ascending
// Input n size to cut
// create a result array using DP bottom up
Build up solutions for 1…n in an array For j = 1 to n do
result[j]:=‐infinity  //initialise the result cell
i := 1
Calculate the best solution for 1 to (n‐1) once only while ((l(i) j) AND (i length(l)) do 
// try to improve with each available length
if (j‐l(i)) equals to zero then
Calculate the best solution for n once only result[j]:=maximum(result[j],p[i])
else     
result[j]:=maximum(result[j],p[i]+result[j‐l(i)])
end if
i := i + 1
end do
End do
Return result
VSV 2021 VCE Algorithmics HESS Unit 4
End Function VSV 2021 VCE Algorithmics HESS Unit 4

2
10/08/2021

Bottom‐Up Dynamic Programming Bottom‐Up Dynamic Prog j i l(i) p[i] Result


1 [‐∞,‐,‐,‐]
Length  i 1 2 3 4 Function DP‐CutResource(p,l,n) 1 1 1 [1,‐,‐,‐]
// Input p an array of prices
Price pi 1 5 8 9 // Input l an array of lengths ascending 2 [1,‐∞,‐,‐]
// Input n size to cut 2 1 1 1 [1,2,‐,‐]
// create a result array using DP bottom up
For j = 1 to n do 2 2 5 [1,5,‐,‐]
result[j]:=‐infinity  //initialise the result cell 3 [1,5,‐∞,‐]
i := 1
while ((l(i) j) AND (i length(l)) do  3 1 1 1 [1,5,6,‐]
// try to improve with each available length
3 2 2 5 [1,5,6,‐]
if (j‐l(i)) equals to zero then
result[j]:=maximum(result[j],p[i]) 3 3 3 8 [1,5,8,‐]
else     
result[j]:=maximum(result[j],p[i]+result[j‐l(i)]) 4 [1,5,8,‐∞]
end if 4 1 1 [1,5,8,9]
i := i + 1
end do 4 2 5 [1,5,8,10]
End do 4 3 8 [1,5,8,10]
Return result
End Function 4 4 9 [1,5,8,10]

Length  i 1 2 3 4
Price pi 1 5 8 9

VSV 2021 VCE Algorithmics HESS Unit 4 VSV 2021 VCE Algorithmics HESS Unit 4

Bottom‐Up Dynamic Programming
Function DP‐CutResource(p,l,n)
// Input p an array of prices
Time Complexity of DP solution
Part 2: Minimax Algorithm
// Input l an array of lengths ascending
// Input n size to cut
// create a result array using DP bottom up For j=1 to n

looking ahead a few levels 
For j = 1 to n do
result[j]:=‐infinity  //initialise the result cell For i=1 to j
i := 1
while ((l(i) j) AND (i length(l)) do  Nested Loop
// try to improve with each available length
if (j‐l(i)) equals to zero then to plan a move
result[j]:=maximum(result[j],p[i]) Inner loop actions execute 
else     
result[j]:=maximum(result[j],p[i]+result[j‐l(i)])
end if 1 + 2  + 3 + 4 + 5 +….n   times
i := i + 1
end do
End do
Return result
End Function
𝑛 𝑛 1
𝑛𝑢𝑚𝑏𝑒𝑟 𝑜𝑓 𝑎𝑐𝑡𝑖𝑜𝑛𝑠 𝑗
2

𝑛𝑢𝑚𝑏𝑒𝑟 𝑜𝑓 𝑎𝑐𝑡𝑖𝑜𝑛𝑠 𝑂 𝑛

VSV 2021 VCE Algorithmics HESS Unit 4 VSV 2021 VCE Algorithmics HESS Unit 4

Mathematicians categorize games Zero‐Sum Games
• Perfect information games like checkers and chess; the board 
shows both players all the information needed to make the  Zero‐sum games are games in which a winner’s payoff 
right decision. is equal to a loser’s loss.  
• Imperfect information games like poker; no player has  For example in chess, one person’s victory is balanced by the 
enough information (the other player’s card are hidden) to  opponent’s loss. Even if the chess game ends in a stalemate, then 
make a guaranteed right decision. neither has gained or lost.  
In a poker game your winnings add up to the sum of losses of your 
opponents.  At the end of the game, poker players as a group are 
no wealthier or poorer than when they started. 

VSV 2021 VCE Algorithmics HESS Unit 4 VSV 2021 VCE Algorithmics HESS Unit 4

3
10/08/2021

Game Tree – showing decisions  Game Tree – showing decisions and 


scores (tic‐tac‐toe) for a few moves 
and scores (rock‐paper‐scissors)
forward.

VSV 2021 VCE Algorithmics HESS Unit 4 VSV 2021 VCE Algorithmics HESS Unit 4

Game Tree – showing decisions and  Looking ahead in the Decision tree


scores (chess) for a few moves  with the Minimax algorithm.
forward.
Generate the decision tree  Work out the best move by 
from this place in the game  the player with minimax. 
for a few levels with the  Where best is based on 
players taking turns. heuristics or prior knowledge.

VSV 2021 VCE Algorithmics HESS Unit 4 VSV 2021 VCE Algorithmics HESS Unit 4

function minimax(node, depth, maximizingPlayer) 
Minimax Algorithm if (depth = 0 or node is a terminal node) then
return the heuristic value of node 
• Minimax is a decision algorithm used  end if
in decision theory for minimizing the  if (maximizingPlayer) then 
possible loss for a worst case  bestValue := −∞ 
(maximum loss) scenario.  for each child of node do 
• Originally formulated for two‐ v := minimax(child, depth − 1, FALSE) 
player zero‐sum games where players  bestValue := max(bestValue, v)
take alternate moves.  end do 
return bestValue
function minimax(node, depth, maximizingPlayer)  else // minimizing player
if (depth = 0 or node is a terminal node) then
bestValue := +∞ 
return the heuristic value of node 
end if
for each child of node do
if (maximizingPlayer) then  v := minimax(child, depth − 1, TRUE) 
// maximize gain for player recursively to (depth‐1)  bestValue := min(bestValue, v) 
else end do
// minimise gain for opponent recursively to (depth‐1) return bestValue
end if end if
End function // Initial call for maximizing player  End function // Initial call for maximizing player 
minimax(origin, depth, TRUE) minimax(origin, depth, TRUE)

VSV 2021 VCE Algorithmics HESS Unit 4 VSV 2021 VCE Algorithmics HESS Unit 4

4
10/08/2021

Minimax Algorithm Minimax Algorithm

VSV 2021 VCE Algorithmics HESS Unit 4 VSV 2021 VCE Algorithmics HESS Unit 4

Proof of Correctness for Divide & 
Part 3: Proof of Correctness by  Conquer designs.
Main Steps
Induction & Contradiction 1. Define your recursive non overlapping sub‐problem. Describe in English what 
your sub‐problem means.
Divide & Conquer 
2. Define the base cases. A recursive algorithm has base cases, and you should 
Dynamic Programming state what they are.

Backtracking 3. Present the recursive cases. Give a mathematical definition of your sub‐
problem in terms of “smaller” sub‐problems that don’t overlap. Therefore it is 
Divide & Conquer.

4. Prove correctness. This will be an inductive proof that your algorithm does 
what it is supposed to. Start by arguing that the base cases return the correct 
result, then for the inductive step, argue why the recursive cases combine to 
solve the overall problem.
VSV 2021 VCE Algorithmics HESS Unit 4 VSV 2021 VCE Algorithmics HESS Unit 4

Divide & Conquer Proof 1 Divide & Conquer Proof 2
Mergesort Divide & Conquer  Mergesort Base Case & Inductive 
Design Step
Algorithm Mergesort(Input List: L) Let T(n) denote the running  Algorithm Mergesort(Input List: L) As a base case, consider 
if |L| = 1 then time of Mergesort(L) when  if |L| = 1 then when length of list L = 1. 
return L L is a list of n elements  return L
else then:  else
This one‐element list is 
divide L into two halves A and B of size n/2 and n/2 respectively. T(n) = 2T(n/2) + O(n) with  divide L into two halves A and B of size n/2 and n/2 respectively.
let A∗ = Mergesort(A) and B∗ = Mergesort(B) base case T(1) = O(1)  let A∗ = Mergesort(A) and B∗ = Mergesort(B) already sorted, and our 
let L∗ be a new empty list let L∗ be a new empty list algorithm correctly 
// merge A* and B* in correct order into L* And therefore the running  // merge A* and B* in correct order into L* returns L as the sorted 
while both A∗ and B∗ are non‐empty do time is O(n log n). while both A∗ and B∗ are non‐empty do list.
if first element of A∗ <  first element of B∗ then if first element of A∗ < first element of B∗ then
append the first element of A∗ onto L∗ and remove it from A∗ Claim. Mergesort(L)  append the first element of A∗ onto L∗ and remove it from A∗
else correctly returns the  else For the induction step, 
append the first element of B∗ onto L∗ and remove it from B∗ elements of L in sorted  append the first element of B∗ onto L∗ and remove it from B∗
end if order.  end if
end while nd while Suppose for any list L of 
if one of A∗ or B∗ is non‐empty then if one of A∗ or B∗ is non‐empty then length < n; Mergesort(L) 
append it to the end of L∗ append it to the end of L∗ correctly sorts L.
end if end if
return L∗ return L∗
end if end if
VSV 2021 VCE Algorithmics HESS Unit 4 VSV 2021 VCE Algorithmics HESS Unit 4

5
10/08/2021

Divide & Conquer Proof 3 Binary Search – Divide & Conquer


Mergesort Induction step
Algorithm Mergesort(Input List: L)
Now consider a list L of length n.  Iterative Binary Search  Proof of correctness by induction 
if |L| = 1 then
return L Algorithm Divide & Conquer T(n)=T(n/2)+O(1), T(1)=O(1)
else
divide L into two halves A and B of size n/2 and n/2 respectively. Mergesort divides L into two halves A and B of  function binary_search(Array, Key) As a base case, consider when length of Array = 1.  For this one‐
let A∗ = Mergesort(A) and B∗ = Mergesort(B) size < n; therefore, A∗ and B∗ are sorted order by  // Array of ordered values
let L∗ be a new empty list
element array, Key can be found if it is there. Since 
our induction hypothesis since the length of each  // Key is the value to find Left=Right=middle=1. Array[middle]=Key if it is in the array.
while both A∗ and B∗ are non‐empty do // floor function always rounds down
if first element of A∗ <first element of B∗ then sub‐list is length < n. Left := 1
append the first element of A∗ onto L∗ and remove it from A∗ For the induction step, 
else Right := length(Array) Suppose for any Array of length < n that is in order smallest to 
append the first element of B∗ onto L∗ and remove it from B∗ The minimum element of L is therefore either the  while (Left ≤ Right) do
end if minimum element of A∗ (which is at the front of A∗) or  largest; Binary Search will find Key if it is there Array[middle]=Key 
end while middle := floor((Left + Right) / 2) for some middle value. Left=1, Right<n to begin with .
the minimum element of B∗ (which is at the front of  if (Array[middle] < Key) then
if one of A∗ or B∗ is non‐empty then B∗).  Left := middle + 1
append it to the end of L∗ By induction when the length of the Array is equal to n, the Array 
end if else if (Array[middle] > Key) then
is in order smallest to largest, the value of Left=1, Right=n to 
In the merge phase, we correctly take whichever  Right := middle ‐ 1
return L∗ begin, then middle is set to floor((1+n)/2).
is smallest as the minimum of L. We do this  else
end if if Array[middle] < Key, Key is in upper part of Array which has a 
repeatedly, always selecting the next minimum  return middle
length < n and is still in order, Left is made larger, Array smaller
element from the front of A∗ or B∗, until we’ve  endif
If Array[middle] > Key, Key is in lower part of Array which has a 
end do
produced the sorted L. length < n and is still in order, Right is made smaller, Array smaller
return unsuccessful
If Array[middle] = Key, Key is found 
End function
Therefore we have shown by induction that  Or the length of the Array is ≤ zero which cannot contain Key.
Mergesort(L) correctly sorts any list L.
VSV 2021 VCE Algorithmics HESS Unit 4 VSV 2021 VCE Algorithmics HESS Unit 4

Proof by Contradiction – Binary Search Proof of Correctness for Dynamic 


Iterative Binary Search 
Algorithm
Proof of correctness by Contradiction 
Divide & Conquer T(n)=T(n/2)+O(1), T(1)=O(1)
Programming designs.
function binary_search(Array, Key) Binary Search is assumed to be false, and does not work 
// Array of ordered values to find a Key.
// Key is the value to find Main Steps
// floor function always rounds down
Left := 1 To make the contradiction we need to show that Binary  1. Define the problem in a way that shows the related over‐
Right := length(Array) Search is working to find a Key, which we can do by  lapping sub‐problems.
while (Left ≤ Right) do induction.
middle := floor((Left + Right) / 2)
if (Array[middle] < Key) then Since Binary Search cannot both work and not work  2. Relate an optimal solution to optimal sub‐solutions
Left := middle + 1
simultaneously, the initial assumption is wrong and Binary 
else if (Array[middle] > Key) then
search works to find a Key must be true.
Right := middle ‐ 1 3. Base case shown
else
return middle
endif 4. Prove correctness by induction filling out the array from the  
end do
return unsuccessful bottom up
End function

VSV 2021 VCE Algorithmics HESS Unit 4 VSV 2021 VCE Algorithmics HESS Unit 4

Bottom‐Up DP– Proof of Correctness Bottom‐Up DP– Proof of Correctness 1


Dynamic Programming Rod‐Cutting Inductive proof
Function DP‐CutResource(p,l,n)
// Input p an array of prices
Length  i 1 2 3 4
Function DP‐CutResource(p,l,n) As a base case, consider when a 
// Input l an array of lengths ascending
// Input n size to cut
Price pi 1 5 8 9 // Input p an array of prices
// create a result array using DP bottom up // Input l an array of lengths ascending length of l(1) is cut. Assume that 
For j = 1 to n do // Input n size to cut l(1)=1 so any integer length can be 
result[j]:=‐infinity  //initialise the result cell // create a result array using DP bottom up
i := 1 For j = 1 to n do found.
while ((l(i) j) AND (i length(l)) do  result[j]:=‐infinity  //initialise the result cell
// try to improve with each available length i := 1
if (j‐l(i)) equals to zero then while ((l(i) j) AND (i length(l)) do  This one‐element array is filled 
result[j]:=maximum(result[j],p[i]) // try to improve with each available length
else      if (j‐l(i)) equals to zero then
with the highest price for this 
result[j]:=maximum(result[j],p[i]+result[j‐l(i)])
end if
result[j]:=maximum(result[j],p[i]) length that is possible, by 
i := i + 1
else      selecting the 
end do result[j]:=maximum(result[j],p[i]+result[j‐l(i)])
End do end if maximum(result[1],p[1]).
Return result i := i + 1
End Function end do
End do For the induction step, 
Return result Suppose for any n‐1 < n that is cut 
End Function
the highest price for this returned 
by DP‐CutResource(p,l,n‐1) and 
Overlapping sub‐problems result[n‐1] is maximum price
Length  i l1 l2 l3 l4
Price pi p1 p2 p3 p4

VSV 2021 VCE Algorithmics HESS Unit 4 VSV 2021 VCE Algorithmics HESS Unit 4

6
10/08/2021

Bottom‐Up DP– Proof of Correctness 2 Proof of Correctness for 


Dynamic Programming Rod‐Cutting Induction Step
Function DP‐CutResource(p,l,n)
// Input p an array of prices
// Input l an array of lengths ascending
The maximum price so far is
stored in result[n‐1]
Backtracking Programming designs.
// Input n size to cut
// create a result array using DP bottom up
For j = 1 to n do For j=1 to n The idea of a backtracking algorithm is to extend partial solutions. 
result[j]:=‐infinity  //initialise the result cell
i := 1
Since n‐1 < n At every stage of the backtracking search there is some current 
while ((l(i) j) AND (i length(l)) do  Starting with l[i=1] to l[i=length] partial solution from which the algorithm attempts to find the full 
// try to improve with each available length result[n] will only be updated with 
if (j‐l(i)) equals to zero then
result[j]:=maximum(result[j],p[i]) a higher value if the price[i]+  solution. 
else      result[n – l[i]] is greater than 
result[j]:=maximum(result[j],p[i]+result[j‐l(i)])
end if result[n] Each variable occurring in the current partial solution is within 
i := i + 1
end do some value of its domain on a path to the full solution.
Therefore result[n] will have the 
End do
Return result highest possible value.
• Past variables – have already been checked for consistency
End Function
• Current variables – which are being checked for consistency
• Future variables – which will be checked for consistency
Length  i l1 l2 l3 l4 • Dead end – variables that have been rejected on extension of 
Price pi p1 p2 p3 p4 solution from current variable.
VSV 2021 VCE Algorithmics HESS Unit 4 VSV 2021 VCE Algorithmics HESS Unit 4

Proof of Correctness for 
Backtracking Programming designs.
Using tree terminology,  if there is 
a decision path from the root to  Current 
variable
the target where each node is a 
partial solution of variables, a tree 
traversal algorithm with  Dead 
End
consistency checks that are  Future Future
correct will find the path. variable variable

Consistency checks can be shown to find the solution using 
induction methods, extending from a partial solution that is a 
current variable to future variables. 
VSV 2021 VCE Algorithmics HESS Unit 4

You might also like