GPS I Love You

Time limit1sMemory limit128 MB

Summary
Find the minimum number of roads to force so that a specified simple route becomes the shortest path favored by the GPS.
Level

Medium7 of 10

Topics
Graph, Shortest path, Dynamic programming, Greedy
Solved
No attempts yet

Problem

Thomas T. Garmin got a GPS for his birthday last year, and he loved it! Unfortunately, sometimes Tom wanted to take a scenic route rather than the shortest one suggested by the GPS. Reading the manual, he found he could override the default path-finding algorithm by specifying roads that the GPS is forced to use when computing a route. After some experimentation, Tom discovered that forcing a single road often sufficed to get the route he wanted. For some windier routes, though, Tom needed to force more roads. Eventually Tom began to worry that he wasted too much time picking roads to force before each trip. Now, instead of enjoying his GPS, he spends his drives agonizing over one question: could he have gotten the GPS to pick the scenic route using fewer forced roads?

Can you save this love affair, or are Tom and his GPS doomed to walk separate paths?

Input

Each test case consists of several lines. The first line contains a single integer n<100n < 100, the number of road endpoints, numbered 00 to n−1n-1. Then follow nn lines, each with nn non-negative integers. If the jj-th value in row ii is positive, it is the length of a road from endpoint ii to endpoint jj; if it is 00, there is no road between those two endpoints.

The next line has the form m  p1  p2  p3  …  pmm\; p_1\; p_2\; p_3\; \dots\; p_m and gives the scenic route Tom wants. The route consists of m−1m-1 roads and runs from endpoint p1p_1 to endpoint pmp_m, visiting p2,p3,…p_2, p_3, \dots in that order. The last test case is followed by a line containing a single 00.

Note that when Tom specifies the roads to force, he specifies both their direction and their order. All routes are simple paths, and all road lengths are at most 100100.

Output

For each test case, output one line:

Case n: k

where kk is the smallest number of roads Tom must force so that the GPS chooses the specified route. Assume that when there are several shortest paths, the GPS always selects the most scenic one. Therefore, if Tom's route is among the shortest paths that use a given set of forced roads, the GPS will pick it.

Examples1

  1. Example 1

    Input
    4
    0 4 0 2
    4 0 2 0
    0 2 0 2
    2 0 2 0
    4 0 3 2 1
    4
    0 4 0 1
    4 0 1 0
    0 1 0 1
    1 0 1 0
    4 0 3 2 1
    0
    
    Expected output
    Case 1: 1
    Case 2: 0