Mobile Service

Time limit3sMemory limit128 MB

Summary
Given a cost matrix and a request sequence, find the minimum total cost of moving three servers to serve each request in order using optimal dynamic programming.
Level

Hard8 of 10

Topics
Dynamic programming, Greedy, Math
Solved
No attempts yet

Problem

A company provides service to customers located in different towns. The company has three service-staff employees. When a request occurs at some location, one employee must move from their current location to the location of the request in order to satisfy it, unless an employee is already there. Only one employee can move at any moment; employees move only in response to a request, and no two employees may occupy the same location.

Moving an employee from location pp to location qq costs a given amount C(p,q)C(p, q). This cost function is not necessarily symmetric, but the cost of not moving is 00, i.e. C(p,p)=0C(p, p) = 0. The company must satisfy the received requests in strict first-come, first-served order.

Decide which employee serves each request so that the total cost of serving the whole sequence of requests is as small as possible, and report that minimum total cost.

Input

The first line contains two integers LL and NN. LL (3≤L≤2003 \le L \le 200) is the number of locations and NN (1≤N≤10001 \le N \le 1000) is the number of requests. Locations are identified by the integers from 11 to LL.

Each of the next LL lines contains LL non-negative integers. The jj-th number on line i+1i+1 is the cost C(i,j)C(i, j), which is less than 20002000.

The last line contains NN integers, the list of requests. Each request is given by the identifier of the location where it occurs. Initially, the three employees are located at locations 11, 22, and 33, respectively.

Output

Print a single integer MM: the minimal total cost of serving the entire sequence of requests.

Examples5

  1. Example 1

    Input
    5 9
    0 1 1 1 1
    1 0 2 3 2
    1 1 0 4 1
    2 1 5 0 1
    4 2 3 4 0
    4 2 4 1 5 4 3 2 1
    
    Expected output
    5
    
  2. Example 2

    Input
    3 5
    0 1 1
    1 0 1
    1 1 0
    1 2 3 1 2
    
    Expected output
    0
    
  3. Example 3

    Input
    4 1
    0 5 7 9
    5 0 3 2
    7 3 0 4
    9 2 4 0
    4
    
    Expected output
    2
    
  4. Example 4

    Input
    4 2
    0 100 100 100
    100 0 100 100
    100 100 0 1
    100 100 1 0
    4 3
    
    Expected output
    2
    
  5. Example 5

    Input
    5 6
    0 3 8 1 9
    2 0 4 7 6
    5 1 0 2 3
    8 4 6 0 1
    7 2 5 9 0
    4 5 1 4 2 5
    
    Expected output
    4