Under construction

Still being built. Things may change

Clear and Present Danger

Interview

Time limit1sMemory limit128 MB

Summary
Given a danger matrix and a required sequence of islands, find the minimum total danger of a walk that visits those islands in order, allowing detours through others.
Level

Medium4 of 10

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

Problem

Farmer John is sailing in search of legendary treasure hidden on one of NN islands, conveniently numbered 11 through NN (1≤N≤1001 \le N \le 100).

The treasure map tells him that, before the treasure will appear, he must travel through a sequence of MM islands A1,A2,…,AMA_1, A_2, \ldots, A_M (2≤M≤100002 \le M \le 10000) in the given order. The route starts at island 11 and ends at island NN (that is, A1=1A_1 = 1 and AM=NA_M = N). He may stop at other islands along the way and may visit the same island more than once, but he must visit A1,A2,…,AMA_1, A_2, \ldots, A_M in exactly this order.

Farmer John wants to avoid pirates and knows the pirate-danger rating dd (0≤d≤1000000 \le d \le 100000) between every pair of islands. The total danger of a route is the sum of the danger ratings of every segment he travels.

Help Farmer John find the least dangerous route that satisfies the treasure map's requirement, and report its total danger.

Input

  • Line 1: Two space-separated integers NN and MM.
  • Next MM lines: line ii contains a single integer AiA_i, the ii-th island Farmer John must visit (A1=1A_1 = 1, AM=NA_M = N).
  • Next NN lines: line ii contains NN integers; the jj-th integer is the danger rating of the path between island ii and island jj. The ii-th integer on line ii is always 00.

Output

  • A single integer: the minimum total danger Farmer John must encounter to obtain the treasure.

Hint

You do not have to travel directly between two consecutive required islands — routing through other islands can be safer. For example, going directly between island 11 and island 22 has danger 55, but the route 1→3→21 \to 3 \to 2 costs only 1+2=31 + 2 = 3. Using the safest path between each consecutive required pair (1→21 \to 2, 2→12 \to 1, 1→31 \to 3) gives a total danger of 3+3+1=73 + 3 + 1 = 7.

Examples1

  1. Example 1

    Input
    3 4
    1
    2
    1
    3
    0 5 1
    5 0 2
    1 2 0
    
    Expected output
    7