Johnny has received 200 dollars from his parents to buy the 10 textbooks listed below. He has been told that he could keep rest of the amount. He decides to make a purchase online. However, prices vary among different online stores:
dollars | Shop 1 | Shop 2 | Shop 3 | Shop 4 | Shop 5 | Shop 6 | Shop 7 | Shop 8 | Shop 9 | Shop 10 |
English | 13 | 19 | 16 | 19 | 19 | 18 | 17 | 16 | 15 | 14 |
Math | 18 | 13 | 17 | 14 | 15 | 16 | 15 | 17 | 18 | 17 |
French | 17 | 14 | 13 | 17 | 16 | 18 | 16 | 17 | 18 | 17 |
History | 19 | 18 | 17 | 13 | 16 | 15 | 15 | 16 | 17 | 14 |
Art | 16 | 14 | 17 | 18 | 13 | 16 | 15 | 16 | 17 | 16 |
Geography | 17 | 17 | 16 | 14 | 15 | 13 | 16 | 17 | 18 | 16 |
Biology | 17 | 14 | 16 | 17 | 15 | 16 | 13 | 18 | 19 | 17 |
Physics | 17 | 16 | 15 | 14 | 17 | 16 | 15 | 13 | 15 | 15 |
Chemistry | 15 | 15 | 16 | 18 | 17 | 15 | 16 | 15 | 13 | 14 |
Music | 16 | 14 | 16 | 18 | 17 | 17 | 15 | 16 | 18 | 13 |
Delivery cost | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 | 4 |
Delivery charge is uniform across all shops--$4 regardless of the number of books purchased in a particular shop. Of course, Johnny could buy zero or multiple books in a shop.
Help Johnny spend as little money as possible on the 10 books, and give his total cost in dollars.
This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try
refreshing the page, (b) enabling javascript if it is disabled on your browser and,
finally, (c)
loading the
non-javascript version of this page
. We're sorry about the hassle.
A naive brute force approach would be to try all possible ways we could have bought the books. That would take O ( shopCount bookCount ) time.
We can do slightly better, i.e, in time O ( 2 shopCount ⋅ bookCount ⋅ shopCount ) .
Our plan is to first generate the set of shops from which we are going to order. Once this set is known, we can tell that the delivery charge is going to be the number of shops in the set, times the delivery charge for each shop. And, once the set of shops is fixed, we can find the best possible shop from which we can buy this book simply by iterating over all the shops in the set.
In pseudocode:
Of course, a deterministic machine cannot guess, which means we have to iterate over all possible subsets of shops. To do this in a compact way, we use a shopCount -bit integer to represent a subset of the shops. We use some bit manipulation hacks to manipulate this sets.
First, we have the data:
And a function to count the number of elements in a set index
And finally, the main program:
To get the result,
The full code is here