You are driving on a long, straight road, on your way to a place whose name is given in destination. After a while, you lose track of how far you've driven and realize that you may even have driven past your destination without noticing. "Don't worry!" says your friend, who is in the car with you, "I have an excellent memory and can remember not only what was written on every road sign that we have passed, but also what order they were in. Let's continue until we see the next road sign and maybe we'll be able to work out how far we still have to go." You agree to his plan, but don't quite trust his memory as much as he clearly does. You decide that you'll believe what he says as long as it is entirely consistent, otherwise you'll try to find somewhere that you can buy a map.
The information written on each sign is a semi-colon separated list, where each element of the list is the name of a place and the distance to that place from the sign separated by a space. For example, if sign i contained "A 10;B 15" (quotes for clarity) and the sign were located a distance of S[i] units down the road, then the place called "A" would be located P["A"] = S[i] + 10 units down the road and the place called "B" would be located P["B"] = S[i] + 15 units down the road. The distances will never be negative, so only places that are at least as far along the road as the sign can be listed. Note that the values in S[] and P[] need not be integers and that places will have distinct names. You are given the information written on sign i as your friend remembers it in signs[i]. Your friend claims to remember the order of the signs too, so if you wrote down the values of S[i] for each sign, they would be in strictly increasing order (no two signs were colocated).
You are currently at the same position as the sign given in the last element of signs. If the information given in signs is consistent, you can determine the remaining distance to your destination and this distance is non-negative, then return this distance. Otherwise, if there is no way that the data given in signs could represent a set of signs and places as described above, or you cannot determine the distance to your destination from the information in the signs, or you have already driven past your destination, return -1 instead.
|