Odev 5
Odev 5
Homework 4
Assigned Thursday, November 11. Your answers must be uploaded to uzak.etu.edu.tr by Monday,
November 22, 23.59.
Problem 1. Bill wants to form a stamp collection. In the small town he lives, there are two stores,
namely A and B that sell stamps. Both stores carry the same n distinct stamps, numbered
from 1 to n. However the price for the same stamp may be different in each store. For each
i ∈ {1, . . . , n}, let a[i] denote the price of the i-th stamp in store A, and b[i] denote the price
of the i-th stamp in store b. Moreover, Bill has a giftcard of x dollars that he can use in store
A, and a giftcard of y dollars that he can use in store B, and he has no other money. (In
other words he can buy stamps only using his giftcards.) Bill’s goal is to buy as many stamps
as possible using his giftcards. In this problem you are asked to help him to maximize the
number of distinct stamps he can buy using his giftcards. The inputs to your algorithm are
two arrays containing n positive integers each, a[1 . . . n] and b[1 . . . n], and two integers x and
y that denote the values of the giftcards. First give a DP formulation to solve this problem.
Then give pseudocode.
Problem 2. Research “Segmented Least Squares Problem” and its dynamic programming solu-
tion. Write in your own words the definition of the problem, explain its dynamic programming
solution and give its DP formulation.
Problem 3. A computer program A and a person B are playing a card game. There are three stacks
of cards, and n1 , n2 and n3 denote the number of cards in the stacks 1, 2 and 3, respectively.
During the game, players A and B take turns. When it is a player’s turn, the player can do
one of the following three moves: (1) Remove 1 card from stack 1. (2) Remove either 1 or 2
cards from stack 2. (3) Remove either 2 or 3 cards from stack 3. The first player who is not
able to make any one of these moves loses. (Try to identify when this can happen). This game
is what is called a solved game whose outcome (win, lose) can be correctly predicted from any
position, given that both players play perfectly. For example, suppose that the initial stack
sizes are (0, 1, 4) and A starts the game. In this case A can force a win. It uses the rule (3)
to remove 2 cards from stack 3, resulting in the stack sizes (0,1,2). B’s only choices are to
remove 1 from stack 2 or 2 from stack 3, resulting in the possible stack sizes (0, 0, 2) and (0,
1, 0). In either case, A can remove the final cards (using either rules (3) or (2), respectively)
leaving B without a move.
Derive a dynamic programming formulation to determine if A can force a win, given the
initial stack sizes, (n1 , n2 , n3 ), and with the assumptions that A plays first and both players
play as well as possible. Give a pseudocode implementation of your DP formulation using
memoization. Run your algorithm on a small example, clearly showing how you construct the
memoization table.