TopCoder problem "MakingPotions" used in SRM 433 (Division II Level Three)

Problem Statement

    An old witch is making a love potion. She has a lot of recipes and each of them has the following form:


where N1, ?, Nk are single-digit integers between 1 and 9, inclusive, S1, ?, Sk are names of ingredients, k is an integer greater than or equal to 1, and S is name of the resulting potion (all names contain only uppercase letters). This means that if she mixes N1 units of S1, ..., Nk units of Sk all together, she will obtain 1 unit of S. There may be multiple recipes for the same potion. In that case, the potion can be obtained using any one of them. The ingredients are also potions, and some of them can be bought at the market.

You want to create 1 unit of the potion called LOVE. You are given String[] recipes, each element of which is a recipe formatted as described above. You are also given a String[] marketGoods and a int[] cost. Each element of marketGoods is the name of a potion you can purchase at the market. The i-th element of cost is the cost of 1 unit of the i-th potion in marketGoods. Return the cheapest cost of obtaining 1 unit of LOVE. If this cost is greater than 1,000,000,000, return 1,000,000,001 instead. If the potion cannot be obtained, return -1 instead.


Parameters:String[], int[], String[]
Method signature:int getCost(String[] marketGoods, int[] cost, String[] recipes)
(be sure your method is public)


-marketGoods will contain between 1 and 50 elements, inclusive.
-Each element of marketGoods will contain between 1 and 50 characters, inclusive.
-Each element of marketGoods will contain only uppercase letters ('A'-'Z').
-All elements of marketGoods will be distinct.
-cost will contain the same number of elements as marketGoods.
-Each element of cost will be between 1 and 100, inclusive.
-recipes will contain between 0 and 50 elements, inclusive.
-Each element of recipes will contain between 4 and 50 characters, inclusive.
-Each element of recipes will contain only uppercase letters ('A'-'Z'), non-zero digits ('1'-'9') and the characters '+' and '='.
-Each element of recipes will be formatted as described in the problem statement.


{100, 1, 30}
Returns: 95
The LOVE potion is sold at the market, but the witch can make it for a lower cost.
{2, 6, 9}
Returns: 76
To obtain LOVE, one must make two units of BEER at a cost of 24 each, and then mix 2 units of WATER, 4 units of HONEY and 2 units of BEER, which will cost a total of 76.
{6, 4}
Returns: -1
The witch doesn't have a LOVE recipe.
Returns: 73
The witch has two LOVE recipes and prefers the first one.
{"OIL", "WATER"}
{60, 70}
Returns: -1
Returns: 1000000001
Returns: -1
Some recipes can be useless.
Returns: 110

Problem url:

Problem stats url:




PabloGilberto , Olexiy , ivan_metelsky

Problem categories:

Greedy, String Parsing