Supermarket
InterviewTime limit1sMemory limit128 MB
Given a shopping list and products in path order, buy the list items in order from later positions at minimum total cost, or report impossible.
- Level
Medium5 of 10
- Topics
- Dynamic programming, Array, Hash map, Greedy
- Solved
- No attempts yet
Problem
Mr. Jones is an exemplary husband. Every Saturday morning Mrs. Jones gives him a list of goods to buy at the supermarket, and he buys exactly what he was asked for, always choosing the brands with the lowest prices. But Mr. Jones hates going to the supermarket on Saturdays, when the aisles are packed with shoppers. He wants to change the way he shops. Instead of walking back and forth to collect the products on his wife's list, he will gather them by going through each aisle only once, picking up the products in the exact order given on the list. He asked you to write a program to help him with this new style of shopping.
Given the products available in the supermarket together with their prices, listed in the order in which Mr. Jones encounters them along his path, and the list of products his wife gave him, your program must determine the least cost he would pay.
Mr. Jones buys the products in the order in which they appear on Mrs. Jones's list, and he never walks back along the aisles. Therefore, if he buys the product at path position as the -th item on the list, the next product to buy is the -th item on the list, and it must be bought from the products that come after position on his path. Note that different brands of the same product may appear separately.
The figure below shows an example. Mr. Jones must buy products 1, 1, 2, 20 (note that product 1 appears twice on the list). For this example the least cost is 21.30. With this new way of shopping it may be impossible to buy every item on the list; in that case your program should warn Mr. Jones.

(a) Mrs. Jones's list

(b) The products with their prices, in the order they appear along Mr. Jones's path
Input
The input consists of several shopping sessions. The first line of each session contains two integers and : is the number of items on Mrs. Jones's list () and is the total number of products available in the supermarket (). The next line contains integers , the products on Mrs. Jones's list (, ). Then lines follow, describing the supermarket products in the order in which Mr. Jones encounters them. Each of these lines contains an integer and a real number , the product identifier and its price (). The end of the input is indicated by a line with .
Output
For each shopping session, print one line with the least cost Mr. Jones would pay. If it is not possible to buy all the items for that session, print the word Impossible. The cost must be printed as a real number with two decimal places, with the last digit rounded. The input will not contain cases where the choice of rounding is significant.