Travelling Tom
Time limit1sMemory limit256 MB
Find the cheapest route that starts at the first listed city, visits every city in the given order using any connecting flights, then returns to the start.
- Level
Medium4 of 10
- Topics
- Shortest path, Graph
- Solved
- No attempts yet
Problem
Tom sells used popsicles from a stand, and business has been slow. He wants to fly around the world and sell his stock in other cities instead. He already has the list of cities he wants to visit and the price of every flight between them, so all that is left is working out what the trip costs.
Tom starts in the first city on the list and visits the cities in the listed order. After the last city he flies back to the city he started from. He may take extra flights through cities that are not next on the list, so a city on the list counts only when he reaches it in the correct relative order. For the list 1 0 2 the route 1 2 0 2 1 is valid, while 1 2 0 1 is not, because city 2 is never reached after city 0.
Compute the smallest total price of such a trip.
Input
The first line contains the number of test cases .
Each test case starts with a line containing the number of cities . Cities are numbered from to . The next line contains integers , the order in which Tom visits the cities. The next lines contain integers each. The -th integer on the -th of those lines is , the price of the flight from city to city . If no flight goes from city to city , then is .
- , and the visiting order is always a permutation of to
- for every city
Output
For each test case, print one line with the smallest total price of the trip. If Tom cannot complete the trip, print impossible instead.