Joisino the magical girl has decided to turn every single digit that exists on this world into 1.
Rewriting a digit i with j (0≤i,j≤9) costs c_{i,j} MP (Magic Points).
She is now standing before a wall. The wall is divided into HW squares in H rows and W columns, and at least one square contains a digit between 0 and 9 (inclusive).
You are given A_{i,j} that describes the square at the i-th row from the top and j-th column from the left, as follows:
 - If A_{i,j}≠-1, the square contains a digit A_{i,j}.
 - If A_{i,j}=-1, the square does not contain a digit.
Find the minimum total amount of MP required to turn every digit on this wall into 1 in the end.

-----Constraints-----
 - 1≤H,W≤200
 - 1≤c_{i,j}≤10^3 (i≠j)
 - c_{i,j}=0 (i=j)
 - -1≤A_{i,j}≤9
 - All input values are integers.
 - There is at least one digit on the wall.

-----Input-----
Input is given from Standard Input in the following format:
H W
c_{0,0} ... c_{0,9}
:
c_{9,0} ... c_{9,9}
A_{1,1} ... A_{1,W}
:
A_{H,1} ... A_{H,W}

-----Output-----
Print the minimum total amount of MP required to turn every digit on the wall into 1 in the end.

-----Sample Input-----
2 4
0 9 9 9 9 9 9 9 9 9
9 0 9 9 9 9 9 9 9 9
9 9 0 9 9 9 9 9 9 9
9 9 9 0 9 9 9 9 9 9
9 9 9 9 0 9 9 9 9 2
9 9 9 9 9 0 9 9 9 9
9 9 9 9 9 9 0 9 9 9
9 9 9 9 9 9 9 0 9 9
9 9 9 9 2 9 9 9 0 9
9 2 9 9 9 9 9 9 9 0
-1 -1 -1 -1
8 1 1 8

-----Sample Output-----
12

To turn a single 8 into 1, it is optimal to first turn 8 into 4, then turn 4 into 9, and finally turn 9 into 1, costing 6 MP.
The wall contains two 8s, so the minimum total MP required is 6×2=12.

Difficulty: interview

Starter code:

Solutions:
from itertools import chain
import numpy as np
import networkx as nx

h, w, *X = map(int, open(0).read().split())
C = np.array(X[:100], dtype=int).reshape((10, 10))
A = np.array(X[100:], dtype=int).reshape((h, w))

G = nx.DiGraph(C)
d = {-1:0}
for i in range(10):
    d[i] = nx.shortest_path_length(G, i, 1, weight='weight')
print(sum(d[a] for a in chain.from_iterable(A)))

import sys
sys.setrecursionlimit(2147483647)
input=sys.stdin.readline
import math
from heapq import heappush, heappop

def solve(h,w,tables,A):
  for i in range(10):
    for j in range(10):
      for k in range(10):
        tables[j][k] = min(tables[j][k], tables[j][i] + tables[i][k])
  cost = 0
  for i in range(h):
    for j in range(w):
      p = A[i][j]
      if p == -1:
        continue
      cost += tables[p][1]
  return cost
  

def main():
  h, w = map(int, input().split(' '))
  tables = []
  for i in range(10):
    tables.append(list(map(int, input().split(' '))))
  A = []
  for _ in range(h):
    A.append(list(map(int, input().split(' '))))
  ans = solve(h, w, tables, A)
  print(ans)
  

def __starting_point():
  main()
__starting_point()

h, w = map(int, input().split())
c = []
for i in range(10):
    c.append(list(map(int, input().split())))
a = []
for i in range(h):
    a.append(list(map(int, input().split())))
cost = [float("inf") for i in range(10)]
flag = [False for i in range(10)]
cost[1] = 0
test = [1]
while test:
    num = test.pop(0)
    flag[num] = True
    for i in range(10):
        cost[i] = min(cost[i], cost[num] + c[i][num])
    temp = [[cost[i], i] for i in range(10)]
    temp.sort()
    for i in range(10):
        if flag[temp[i][1]] == True:
            continue
        else:
            test.append(temp[i][1])
            break
ans = 0
for i in range(h):
    for j in range(w):
        if a[i][j] == -1:
            continue
        else:
            ans += cost[a[i][j]]
print(ans)

import sys
input = sys.stdin.readline


def read():
    H, W = list(map(int, input().strip().split()))
    N = 10
    C = []
    for i in range(N):
        c = list(map(int, input().strip().split()))
        C.append(c)
    A = []
    for i in range(H):
        a = list(map(int, input().strip().split()))
        A.append(a)
    return H, W, N, C, A


def warshall_floyd(N, G, INF=10**7):
    for k in range(N):
        for i in range(N):
            for j in range(N):
                G[i][j] = min(G[i][j], G[i][k] + G[k][j])
    return G


def solve(H, W, N, C, A):
    D = warshall_floyd(N, C)
    ans = 0
    for i in range(H):
        for j in range(W):
            a = A[i][j]
            if a >= 0:
                ans += D[a][1]
    return ans


def __starting_point():
    inputs = read()
    outputs = solve(*inputs)
    if outputs is not None:
        print(("%s" % str(outputs)))

__starting_point()

icase=0
if icase==0:
    h,w=list(map(int,input().split()))
    dp=[[0]*10 for i in range(10)]
    for i in range(10):
        dp[i]=list(map(int,input().split()))
    a=[]
    for i in range(h):
        a.extend(list(map(int,input().split())))
elif icase==1:
    h,w=2,4
    dp=[[0, 9, 9, 9, 9, 9, 9, 9, 9, 9], 
       [9, 0, 9, 9, 9, 9, 9, 9, 9, 9],
       [9, 9, 0, 9, 9, 9, 9, 9, 9, 9],
       [9, 9, 9, 0, 9, 9, 9, 9, 9, 9],
       [9, 9, 9, 9, 0, 9, 9, 9, 9, 2],
       [9, 9, 9, 9, 9, 0, 9, 9, 9, 9],
       [9, 9, 9, 9, 9, 9, 0, 9, 9, 9],
       [9, 9, 9, 9, 9, 9, 9, 0, 9, 9],
       [9, 9, 9, 9, 2, 9, 9, 9, 0, 9],
       [9, 2, 9, 9, 9, 9, 9, 9, 9, 0]]

    a=[-1, -1, -1, -1, 8, 1, 1, 8]

from collections import Counter
ac=Counter(a)

n=10
for k in range(n):
    for i in range(n):
        for j in range(n):
            dp[i][j]=min(dp[i][j],dp[i][k]+dp[k][j])

icnt=0
for i in range(10):
    if ac[i]>0:
        icnt+=dp[i][1]*ac[i]  

print(icnt)      


from networkx import *
h,w=map(int,input().split())
G=DiGraph()
G.add_nodes_from(range(10))
C=[[*map(int,input().split())]for _ in "_"*10]
G.add_weighted_edges_from([(i,j,C[i][j])for i in range(10)for j in range(10)])
S=[single_source_dijkstra_path_length(G,i)[1]for i in range(10)]
A=[[*map(int,input().split())]for _ in "_"*h]
print(sum(S[abs(x)] for a in A for x in a))

import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time, copy,bisect
from operator import itemgetter
from heapq import heappush, heappop
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

stdin = sys.stdin

ni = lambda: int(ns())
nf = lambda: float(ns())
na = lambda: list(map(int, stdin.readline().split()))
nb = lambda: list(map(float, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces


H, W = na()
c = [na() for _ in range(10)]
A = [na() for _ in range(H)]
adj = [[] for _ in range(10)]

c = np.array(c)
d = shortest_path(c)
ans = 0
for y in range(H):
    for x in range(W):
        if A[y][x] != -1:
            #print(ans)
            ans += d[A[y][x]][1]
print((int(ans)))



# -*- coding: utf-8 -*-
import sys
from collections import deque, defaultdict, namedtuple
import heapq
from math import sqrt, factorial, gcd, ceil, atan, pi
def input(): return sys.stdin.readline()[:-1] # warning not \n
# def input(): return sys.stdin.buffer.readline()[:-1] # warning bytes
# def input(): return sys.stdin.buffer.readline().strip() # warning bytes
# def input(): return sys.stdin.buffer.readline().decode('utf-8').strip()
import string
import operator
import random
# string.ascii_lowercase
from bisect import bisect_left, bisect_right
from functools import lru_cache, reduce
MOD = int(1e9)+7
INF = float('inf')


def solve():
    n, m = [int(x) for x in input().split()]
    p = []
    for _ in range(10):
        p.append([int(x) for x in input().split()])

    stack = set()
    def dfs(v):
        if v == 1:
            return 0
        stack.add(v)
        for to in range(10):
            if to == v or to in stack: continue
            if p[v][to] < p[v][1]:
                p[v][1] = min(p[v][1], dfs(to) + p[v][to])
        stack.remove(v)
        return p[v][1]

    for i in range(10):
        dfs(i)

    ans = 0
    for _ in range(n):
        row = [int(x) for x in input().split()]
        for e in row:
            if e == -1 or e == 1: continue
            ans += p[e][1]
    print(ans)



T = 1
# T = int(input())
for case in range(1,T+1):
    ans = solve()


"""

dp[num_changes][blue_placed]


abba



"""


from collections import defaultdict
from heapq import heappop, heappush


class Graph(object):
    """
    隣接リストによる有向グラフ
    """

    def __init__(self):
        self.graph = defaultdict(list)

    def __len__(self):
        return len(self.graph)

    def add_edge(self, src, dst, weight=1):
        self.graph[src].append((dst, weight))

    def get_nodes(self):
        return self.graph.keys()


class Dijkstra(object):
    """
    ダイクストラ法（二分ヒープ）による最短経路探索
    計算量: O((E+V)logV)
    """

    def __init__(self, graph, start):
        self.g = graph.graph

        # startノードからの最短距離
        # startノードは0, それ以外は無限大で初期化
        self.dist = defaultdict(lambda: float('inf'))
        self.dist[start] = 0

        # 最短経路での1つ前のノード
        self.prev = defaultdict(lambda: None)

        # startノードをキューに入れる
        self.Q = []
        heappush(self.Q, (self.dist[start], start))

        while self.Q:
            # 優先度（距離）が最小であるキューを取り出す
            dist_u, u = heappop(self.Q)
            if self.dist[u] < dist_u:
                continue
            for v, weight in self.g[u]:
                alt = dist_u + weight
                if self.dist[v] > alt:
                    self.dist[v] = alt
                    self.prev[v] = u
                    heappush(self.Q, (alt, v))

    def shortest_distance(self, goal):
        """
        startノードからgoalノードまでの最短距離
        """
        return self.dist[goal]

    def shortest_path(self, goal):
        """
        startノードからgoalノードまでの最短経路
        """
        path = []
        node = goal
        while node is not None:
            path.append(node)
            node = self.prev[node]
        return path[::-1]
h,w = map(int,input().split())
g = Graph()
for i in range(10):
    c = list(map(int,input().split()))
    for j in range(10):
        src,dst,weight = i,j,c[j]
        g.add_edge(src, dst, weight)

ans = 0
for y in range(h):
    tmp = list(map(int,input().split()))
    for x in range(w):
        if tmp[x] != -1 and tmp[x] != 1:
            d = Dijkstra(g, tmp[x])
            ans += d.shortest_distance(1)
print(ans)

import copy
L=[[j for j in range(10)] for i in range(10)]
H,W=map(int,input().split())
costs=list()
costs2=list()
for i in range(10):
  L1=list(map(int,input().split()))
  costs.append(L1[1])
  costs2.append(L1[1])
  L[i]=L1
for i in range(12):#繰り返し
  for j in range(10):#costsのそれぞれに対し
    for k in range(10):#costs[j]=min(costs[j],costs[k]+jからkのコスト
      costs2[j]=min(costs2[j],costs[k]+L[j][k])
  costs=copy.copy(costs2)
costs.append(0)
s=0
for i in range(H):
  A=list(map(int,input().split()))
  s+=sum([costs[i] for i in A])
print(s)

import heapq
h, w = map(int, input().split())
c = [list(map(int, input().split())) for _ in range(10)]
a = [list(map(int, input().split())) for _ in range(h)]
flag = [[1 for _ in range(10)] for _ in range(10)]
for i in range(10):
    que = [[0, i]]
    while que:
        now = heapq.heappop(que)
        flag[i][now[1]] = 0
        for j in range(10):
            if flag[i][j]:
                heapq.heappush(que, [c[i][now[1]]+ c[now[1]][j], j])
                if c[i][now[1]]+c[now[1]][j] < c[i][j]:
                    c[i][j] = c[i][now[1]]+ c[now[1]][j]

ans = 0      
for i in range(h):
    for j in range(w):
        if a[i][j] != -1:
            ans += c[a[i][j]][1]
print(ans)

from collections import defaultdict

H, W = list(map(int, input().split()))

V = 10

dists = []

for _ in range(V):
    dists.append(list(map(int, input().split())))

count = defaultdict(int)

for _ in range(H):
    for i in map(int, input().split()):
        count[i] += 1

for k in range(V):
    for i in range(V):
        for j in range(V):
            dists[i][j] = min(dists[i][j], dists[i][k] + dists[k][j])


ans = 0

for k, v in list(count.items()):
    if k == -1 or k == 1:
        continue
    ans += v * dists[k][1]
print(ans)



from itertools import chain
import numpy as np
import networkx as nx

X = iter(open(0).readlines())
h, w = map(int, next(X).split())
C = np.zeros((10, 10), dtype=int)
for i in range(10):
    for j, c in enumerate(map(int, next(X).split())):
        C[i, j] = c
A = np.zeros((h, w), dtype=int)
for i in range(h):
    for j, a in enumerate(map(int, next(X).split())):
        A[i, j] = a

G = nx.DiGraph(C)
d = {-1:0}
for i in range(10):
    d[i] = nx.shortest_path_length(G, i, 1, weight='weight')
print(sum(d[a] for a in chain.from_iterable(A)))

from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf,comb
from itertools import accumulate,groupby,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from queue import Queue,LifoQueue,PriorityQueue
from copy import deepcopy
from time import time
from functools import reduce
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

h, w = MAP()
c = []
for i in range(10):
    c.append(LIST())
a = []
for i in range(h):
    a.append(LIST())

chk = True
while chk:
    chk = False
    for i in range(10):
        for j in range(10):
            for k in range(10):
                if c[i][j] > c[i][k]+c[k][j]:
                    c[i][j] = c[i][k]+c[k][j]
                    chk = True

ans = 0
for i in range(h):
    for j in range(w):
        if a[i][j] != -1:
            ans += c[a[i][j]][1]
print(ans)

"""
きょうぎぷろぐらみんぐ！！！！！！
競プロ競プロ競プロ競プロ競プロ競プローーーーー！！！！！！！
hshs！！ﾊｱﾊｱ！！興奮興奮！！！！うおおおおおおお！！！
競プロの重要性！！ｺﾞﾝｺﾞﾝｺﾞﾝｺﾞﾝ(頭を難易度の壁に打ち付ける音)
うおおおおおおお！！競プロの重要性！！
"""
from scipy.sparse.csgraph import shortest_path
from scipy.sparse import csr_matrix
h,w=list(map(int,input().split()))
num=[list(map(int,input().split())) for _ in range(10)]
num=csr_matrix(num)
ans=shortest_path(num)
ans=ans.tolist()
ans2=[0]*10
for i in range(10):
    ans2[i]=int(ans[i][1])
ans3=0
for i in range(h):
    a=list(map(int,input().split()))
    for j in range(w):
        if a[j]!=-1:
            ans3+=ans2[a[j]]
print(ans3)


def main():
    inf=float("inf")
    h,w=map(int,input().split())
    lst=[list(map(int,input().split())) for _ in range(10)]
    dp1=[[inf]*10 for _ in range(10)]
    
    for i in range(10):
        for j in range(10):
            dp1[i][j]=lst[i][j]
    
    for k in range(1,11):
        dp2=[dp1[i][:] for i in range(10)]
        for i in range(10):
            for j in range(10):
                if dp2[i][j]>dp2[i][k-1]+dp2[k-1][j]:
                    dp1[i][j]=dp2[i][k-1]+dp2[k-1][j]

    wall=[list(map(int,input().split())) for _ in range(h)]
    sm=0
    for i in range(h):
        for j in range(w):
            if wall[i][j]==-1 : continue
            sm+=dp1[wall[i][j]][1]

    print(sm)
    
main()

#ワシャフ
INF = 10**9

H,W = map(int,input().split())

#iからjにするのに必要な魔力量
c = [list(map(int,input().split())) for i in range(10)]

dp = [[(INF if i!=j else 0) for j in range(10)]for i in range(10)]
for k in range(0,10,1):
    for i in range(0,10,1):
        for j in range(0,10,1):
            c[i][j] = min(c[i][j],c[i][k]+c[k][j])


A = [list(map(int,input().split())) for i in range(H)]
ans = 0
for i in range(H):
    for j in range(W):
        if A[i][j]>-1:
            ans += c[A[i][j]][1]
print(ans)

H, W = map(int, input().split())
C = [list(map(int, input().split())) for _ in range(10)]
for i in range(10):
    for k in range(10):
        for l in range(10):
            C[k][l] = min(C[k][l], C[k][i]+C[i][l])
ans = 0
for _ in range(H):
    k = list(map(int, input().split()))
    for i in k:
        if i == -1:
            continue
        ans += C[i][1]
print(ans)

def warshall_floyd():
    for middle in range(10):
        for start in range(10):
            for end in range(10):
                costs[start][end] = min(costs[start][end], costs[start][middle] + costs[middle][end])


H, W = map(int, input().split())
costs = []

for i in range(10):
    costs.append(list(map(int, input().split())))

warshall_floyd()

# print(*costs, sep='\n')
ans = 0
for i in range(H):
    wall = list(map(int, input().split()))
    for num in wall:
        if num != -1:
            ans += costs[num][1]
print(ans)

h, w = map(int, input().split())

r = range(10)
c = [[int(i) for i in input().split()] for _ in r]
a = [[int(i) for i in input().split()] for _ in range(h)]

for k in r:
    for i in r:
        for j in r:
            c[i][j] = min(c[i][j], c[i][k] + c[k][j])
else:
    print(sum(c[i][1] for i in sum(a, []) if i != -1))

h, w = map(int, input().split())
a = []
c = []
for i in range(10):
    c.append(list(map(int, input().split())))
for i in range(h):
    a.append(list(map(int, input().split())))


for k in range(10):
    for i in range(10):
        for j in range(10):
            if c[i][j] > c[i][k] + c[k][j]:
                c[i][j] = c[i][k] + c[k][j]
ans = 0
for i in range(h):
    for j in range(w):
        if a[i][j] >= 0:
            ans += c[a[i][j]][1]

print(ans)

H, W = [int(_) for _ in input().split()]
C = [[int(_) for _ in input().split()] for _ in range(10)]
A = [[int(_) for _ in input().split()] for _ in range(H)]

for k in range(10):
    for i in range(10):
        for j in range(10):
            C[i][1] = min(C[i][1], C[i][j] + C[j][1])

ans = 0
for h in range(H):
    for w in range(W):
        if A[h][w] != -1:
            v = A[h][w]
            ans += C[v][1]
print(ans)


H, W = list(map(int, input().split()))

C = []
for i in range(10):
    tmp = list(map(int, input().split()))
    C.append(tmp)

A = []
for i in range(H):
    tmp = list(map(int, input().split()))
    A.append(tmp)

# ワーシャルフロイド法で各数値から各数値への最小コストを求める
for i in range(10):  # 経由する頂点
    for j in range(10):  # 始点
        for k in range(10):  # 終点
            C[j][k] = min(C[j][k], C[j][i]+C[i][k])

ans = 0
for h in range(H):
    for w in range(W):
        if A[h][w] == -1 or A[h][w] == 1:
            continue

        ans += C[A[h][w]][1]
print(ans)


H,W = map(int,input().split())
C = [list(map(int,input().split())) for i in range(10)]
A = [list(map(int,input().split())) for i in range(H)]

for k in range(10):
    for i in range(10):
        for j in range(10):
            C[i][j] = min(C[i][j], C[i][k] + C[k][j])
ans = 0
for row in A:
    for a in row:
        if a == -1: continue
        ans += C[a][1]
print(ans)

import sys
input = sys.stdin.readline
def __starting_point():
    H,W = map(int,input().split())
    V = 10
    edges = []
    for i in range(10):
        c = list(map(int,input().split()))
        edges.append([(j,c[j]) for j in range(10)])
    INF = float("inf")
    dp = [[INF]*V for _ in range(V)]
    for i in range(V):
        for j, w in edges[i]:
            dp[i][j] = w

    for k in range(V):
        for i in range(V):
            for j in range(V):
                dp[i][j] = min(dp[i][j], dp[i][k]+dp[k][j])
    ans = 0
    for _ in range(H):
        for x in map(int,input().split()):
            if x >= 0:
                ans += dp[x][1]
    print(ans)
__starting_point()

import sys
sys.setrecursionlimit(10 ** 9)
# input = sys.stdin.readline    ####
def int1(x): return int(x) - 1
def II(): return int(input())
def MI(): return list(map(int, input().split()))
def MI1(): return list(map(int1, input().split()))
def LI(): return list(map(int, input().split()))
def LI1(): return list(map(int1, input().split()))
def LLI(rows_number): return [LI() for _ in range(rows_number)]
def MS(): return input().split()
def LS(): return list(input())
def LLS(rows_number): return [LS() for _ in range(rows_number)]
def printlist(lst, k=' '): print((k.join(list(map(str, lst)))))
INF = float('inf')
# from math import ceil, floor, log2
# from collections import deque, defaultdict
# from itertools import combinations as comb, combinations_with_replacement as comb_w, accumulate, product, permutations
# from heapq import heapify, heappop, heappush
import numpy as np    # cumsum
# from bisect import bisect_left, bisect_right



def solve():
    H, W = MI()
    dist = LLI(10)
    N = 10

    # dist = [[INF]*10 for _ in range(10)]
    # for i in range(N):
    #     dist[i][1] = C[i, 1]

    for k in range(N):
        for i in range(N):
            for j in range(N):
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

    ans = 0
    for i in range(H):
        for r in LI():
            if r != -1:
                ans += dist[r][1]
    print(ans)




def __starting_point():
    solve()


__starting_point()

import sys
input = sys.stdin.readline

import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix

H,W = map(int,input().split())
costs = []
for i in range(10):
    cost = list(map(int,input().split()))
    costs.append(cost)

cost_array = np.array(costs)
counter = [0]*10
for i in range(H):
    wall = list(map(int,input().split()))
    for j in wall:
        if j != -1:
            counter[j] += 1
mincost = shortest_path(cost_array)
ans = 0
for i in range(10):
    ans += counter[i] * mincost[i][1]
print(int(ans))

from heapq import heappush, heappop
def main():
    H, W = list(map( int, input().split()))
    C = [ list( map( int, input().split())) for _ in range(10)]
    A = [ list( map( int, input().split())) for _ in range(H)]
    h = [(0,1)]
    V = [-1]*10
    while h:
        # print(h)
        m, n = heappop(h)
        if V[n] > -1:
            continue
        V[n] = m
        for i in range(10):
            if V[i] == -1:
                heappush(h, (m+C[i][n],i))
    # print(V)
    ans = 0
    for a in A:
        for b in a:
            if b > -1:
                ans += V[b]
    print(ans)
    
def __starting_point():
    main()

__starting_point()

#!/usr/bin/env python3
def main():
    H, W = list(map(int, input().split()))
    max_num = 10
    c = [list(map(int, input().split())) for _ in range(max_num)]
    A = [list(map(int, input().split())) for _ in range(H)]

    for k in range(max_num):
        for i in range(max_num):
            for j in range(max_num):
                c[i][j] = min(c[i][j], c[i][k] + c[k][j])

    ans = 0
    for row in A:
        for a in row:
            if a == -1:
                continue
            ans += c[a][1]
    print(ans)


def __starting_point():
    main()

__starting_point()

import numpy as np
H, W = (int(x) for x in input().split())
C = np.array([[int(x) for x in input().split()] for _ in range(10)])
A = [[int(x) if int(x) >= 0 else 1 for x in input().split()] for _ in range(H)]
from scipy.sparse.csgraph import dijkstra
C = dijkstra(C,directed=True) #有向グラフの経路圧縮（ダイクストラ法）
ans = sum(sum(C[x,1] for x in A))
print(int(ans))

h, w = map(int, input().split())

inf = 10 ** 20
d = [list(map(int, input().split())) for _ in range(10)]

for k in range(10):
    for i in range(10):
        for j in range(10):
            d[i][j] = min(d[i][j], d[i][k] + d[k][j])

ans = 0
for _ in range(h):
    row = list(map(int, input().split()))
    for num in row:
        if num == -1:
            continue
        ans += d[num][1]

print(ans)

from copy import copy
h, w = map(int, input().split())
data = [list(map(int, input().split())) for _ in range(10)]

c = [list(map(int, input().split())) for _ in range(h)]

d = copy(data)
def cnt_set(d):
    for k in range(10):
        for i in range(10):
            for j in range(10):
                d[i][j] = min(d[i][j], d[i][k] + d[k][j])
cnt_set(d)
ans = 0

for i in range(h):
    for j in range(w):
        if c[i][j] == -1:
            continue
        ans += d[c[i][j]][1]

print(ans)

import heapq
H,W = map(int, input().split())
C = []
for i in range(10):
    C.append(list(map(int, input().split())))
INF = float("inf")

def dfs(x):
    memo = [INF]*10
    memo[x] = 0
    hq = [(0,x)]
    heapq.heapify(hq)
    while hq:
        cost,step = heapq.heappop(hq)
        if cost > memo[step]:
            continue
        for j,c in enumerate(C[step]):
            if memo[j] > memo[step] + c:
                memo[j] = memo[step] + c
                heapq.heappush(hq,(memo[j],j))
    return memo[1]

A = [0]*10
for h in range(H):
    for w in map(int, input().split()):
        if w == -1:
            continue
        else:
            A[w] += 1
ans = 0
for number, a in enumerate(A):
    ans += a*dfs(number)
print(ans)

from collections import Counter
from itertools import product

def main():
    with open(0) as f:
        H, W = map(int, f.readline().split())
        C = [list(map(int, f.readline().split())) for _ in range(10)] 
        A = Counter(map(int, f.read().split()))

    r10 = range(10)
    for k,i,j in product(r10, r10, r10):
        C[i][j] = min(C[i][j], C[i][k]+C[k][j])

    ans = sum(C[key][1]*value for key,value in A.items() if key != -1)
    print(ans)

main() 

H,W = map(int,input().split())
Cls = []
for i in range(10):
    Cls.append(list(map(int,input().split())))
for k in range(10):
    for i in range(10):
        for j in range(10):
            Cls[i][j] = min(Cls[i][j], Cls[i][k] + Cls[k][j])
costls = []
for i in range(10):
    costls.append(Cls[i][1])
numls = []
for i in range(H):
    numls += list(map(int,input().split()))
ans = 0
for i in range(H*W):
    if numls[i] == -1:
        continue
    ans += costls[numls[i]]
print(ans)

H,W=map(int,input().split())
C=[list(map(int,input().split()))for _ in range(10)]
A=[list(map(int,input().split()))for _ in range(H)]

for k in range(10):#経由する頂点
    for i in range(10):#始点
        for j in range(10):#終点
            C[i][j] = min(C[i][j], C[i][k] + C[k][j])
ans=0
for aa in A:
    for a in aa:
        if a==-1:
            ans+=0
        else:
            ans+=C[a][1]
print(ans)

#from statistics import median
#import collections
#aa = collections.Counter(a) # list to list || .most_common(2)で最大の2個とりだせるお a[0][0]
from math import gcd
from itertools import combinations,permutations,accumulate, product # (string,3) 3回
#from collections import deque
from collections import deque,defaultdict,Counter
import decimal
import re
import math
import bisect
import heapq
#
#
#
# pythonで無理なときは、pypyでやると正解するかも！！
#
#
# my_round_int = lambda x:np.round((x*2 + 1)//2)
# 四捨五入g
#
# インデックス系
# int min_y = max(0, i - 2), max_y = min(h - 1, i + 2);
# int min_x = max(0, j - 2), max_x = min(w - 1, j + 2);
#
#
import sys
sys.setrecursionlimit(10000000)
mod = 10**9 + 7
#mod = 9982443453
#mod = 998244353
INF = float('inf')
from sys import stdin
readline = stdin.readline
def readInts():
  return list(map(int,readline().split()))
def readTuples():
    return tuple(map(int,readline().split()))
def I():
    return int(readline())
class WarshallFloyd(object):
    def __init__(self):
        self.max_v = 10
        self.min_dist = [readInts() for _ in range(10)]
    def compute(self):
        for k,i,j in product(list(range(self.max_v)), repeat = 3):
            # i -> j と i -> k -> j のうち、長くない方の距離
            self.min_dist[i][j] = min(self.min_dist[i][j], self.min_dist[i][k] + self.min_dist[k][j])
    def solve(self, n):
        if n == 1:
            return 0
        else:
            return self.min_dist[n][1]
h,w = readInts()
w = WarshallFloyd()
w.compute()
ans = 0
A = [readInts() for _ in range(h)]
for a in A:
    for i in a:
        if i == -1:
            continue
        ans += w.solve(i)
print(ans)


from networkx import *
h,w=map(int,input().split());r=range(10);G=DiGraph();G.add_nodes_from(r);C=[[*map(int,input().split())]for _ in r];G.add_weighted_edges_from([(i,j,C[i][j])for i in r for j in r]);S=[single_source_dijkstra_path_length(G,i)[1]for i in r];A=[[*map(int,input().split())]for _ in "_"*h];print(sum(S[abs(x)] for a in A for x in a))

from collections import defaultdict

h,w=map(int,input().split())
c=[]
dic=defaultdict(int)
for _ in range(10): c.append(list(map(int,input().split())))
for _ in range(h):
    temp=list(map(int,input().split()))
    for i in temp: dic[i]+=1
for k in range(10):
    for i in range(10):
        for j in range(10): c[i][j]=min(c[i][j],c[i][k]+c[k][j])
ans=0
for item in dic.items():
    if item[0]>=0: ans+=item[1]*c[item[0]][1]
print(ans)

from itertools import chain
import numpy as np
import networkx as nx

h, w, *X = map(int, open(0).read().split())
C = np.array(X[:100], dtype=int).reshape((10, 10)).T
A = np.array(X[100:], dtype=int).reshape((h, w))

G = nx.DiGraph(C)
d = {-1:0}
d.update(nx.single_source_dijkstra_path_length(G, 1, weight='weight'))
print(sum(d[a] for a in chain(*A)))

h, w = list(map(int, input().split()))
c = [list(map(int, input().split())) for _ in range(10)]
num = [0]*10
for _ in range(h):
    a = list(map(int, input().split()))
    for i in a:
        if i == -1:
            continue
        num[i] += 1
#a = [list(map(int, input().split())) for _ in range(h)]
#print(num)
for i in range(10):
    for j in range(10):
        for k in range(10):
                c[j][k] = min(c[j][k], c[j][i]+c[i][k])
#print(c)
print((sum(num[x]*c[x][1] for x in range(10))))


H,W = map(int,input().split())
c = [list(map(int,input().split())) for i in range(10)]
A = [list(map(int,input().split())) for i in range(H)]
ma = [1001]*10
ma[1] = 0
use = [i for i in range(10)]
use.remove(1)
from itertools import permutations
for i in range(1,10):
    l = list(permutations(use,i))
    for j in l:
        cost =0
        first = pre = j[0]
        border = ma[first]
        k = 1
        while cost < border and k < i:
            cost += c[pre][j[k]]
            pre = j[k]
            k += 1
        cost += c[pre][1]
        ma[first] = min(border,cost)
ans = 0
for i in A:
    for j in i:
        if j != -1:
            ans += ma[j]
print(ans)

from itertools import chain
import numpy as np
import networkx as nx

h, w, *X = map(int, open(0).read().split())
C = np.array(X[:100], dtype=int).reshape((10, 10))
A = np.array(X[100:], dtype=int).reshape((h, w))

G = nx.DiGraph(C)
d = {-1:0}
for i in range(10):
    d[i] = nx.shortest_path_length(G, i, 1, weight='weight')
print(sum(d[a] for a in chain(*A)))

from itertools import chain
import numpy as np
import networkx as nx

X = iter(open(0).readlines())
h, w = map(int, next(X).split())
C = np.zeros((10, 10), dtype=int)
for i in range(10):
    for j, c in enumerate(map(int, next(X).split())):
        C[i, j] = c
A = np.zeros((h, w), dtype=int)
for i in range(h):
    for j, a in enumerate(map(int, next(X).split())):
        A[i, j] = a

G = nx.DiGraph(C)
d = {}
for i in range(10):
    if i == 1:
        continue
    d[i] = nx.shortest_path_length(G, i, 1, weight='weight')

s = 0
for a in chain.from_iterable(A):
    if a == -1 or a == 1:
        continue
    s += d[a]
print(s)

H , W = map(int,input().split())
c = [list(map(int,input().split())) for i in range(10)]
for k in range(10):
  for i in range(10):
    for j in range(10):
      if c[i][j] > c[i][k] + c[k][j]:
        c[i][j] = c[i][k] + c[k][j]
s = 0
for i in range(H):
  a = list(map(int,input().split()))
  for j in range(W):
    if a[j] == -1:
      a[j] = 1
    s += c[a[j]][1]
print(s)    

import sys, math
from collections import deque
sys.setrecursionlimit(10**9)

def input():
    return sys.stdin.readline()[:-1]

def mi():
    return map(int, input().split())

def ii():
    return int(input())

def i2(n):
    tmp = [list(mi()) for i in range(n)]
    return [list(i) for i in zip(*tmp)]

def main():
    H, W = mi()
    c = [list(mi()) for i in range(10)]
    A = [list(mi()) for i in range(H)]

    for k in range(10):
        for i in range(10):
            for j in range(10):
                # i→k→j
                c[i][j] = min(c[i][j], c[i][k] + c[k][j])


    ans = 0
    for h in range(H):
        for w in range(W):
            if A[h][w] == -1:
                continue
        
            ans += c[A[h][w]][1]

    print(ans)
    

def __starting_point():
    main()
__starting_point()

# -*- coding: utf-8 -*-
from scipy.sparse.csgraph import shortest_path, dijkstra, floyd_warshall, bellman_ford, johnson
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
import sys
from collections import deque
from collections import defaultdict
import heapq
import collections
import itertools
import bisect
import copy
import math
sys.setrecursionlimit(10**6)

# lis_of_lis = [[] for _ in range(N)]


def zz(): return list(map(int, sys.stdin.readline().split()))


def z(): return int(sys.stdin.readline())


def S(): return sys.stdin.readline()[:-1]


def C(line): return [sys.stdin.readline() for _ in range(line)]


H, W = zz()
C = []
for i in range(10):
    C.append(zz())
A = []
num_lis = [0]*10
for i in range(H):
    a = zz()
    for a_ in a:
        if (a_ == -1):
            continue
        num_lis[a_] += 1
    A.append(a)
# 1->1, 2->1, 3->1 にするためのコストを計算する
# cost = [0]*10
# for num in range(2, 10):
#     min_cost = C[num][1]
a = floyd_warshall(C)
ans = 0
for i, num in enumerate(num_lis):
    ans += a[i, 1]*num
print((int(ans)))


from itertools import permutations
from heapq import heappush,heappop

INF=10**12

def dijkstra(G, start = 0, INF=INF):
    
    d = [INF for i in range(len(G))]
    d[start] = 0
    
    que = []
    heappush(que, (0, start))

    while len(que) != 0:
        p = heappop(que)
        v = p[1]
        
        if d[v] < p[0]:
            continue
            
        for u in G[v].keys():
            if d[u] > d[v] + G[v][u]:
                d[u] = d[v] + G[v][u]
                heappush(que, (d[u], u))
    
    return d

H,W=map(int,input().split())
c=[list(map(int,input().split())) for _ in range(10)]
A=[list(map(int,input().split())) for _ in range(H)]

G=[{} for _ in range(10)]
for i in range(10):
  for j in range(10):
    G[i][j] = c[i][j]

dist=[0]*10
for i in range(10):
  d = dijkstra(G,i)
  dist[i] = d[1]

ans=0
for i in range(H):
  for j in range(W):
    if A[i][j] != -1:
      ans += dist[A[i][j]]

print(ans)

import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix

h, w = map(int,input().split())

c = []
for i in range(10):
    c.append(list(map(int, input().split())))

csr = csr_matrix(c)

a = []
for i in range(h):
    a.append(list(map(int, input().split())))

cost = floyd_warshall(csr)[:,1]

ans = 0
for i in range(h):
    for j in range(w):
        if a[i][j] > -1:
            ans += int(cost[a[i][j]])
print(ans)

from itertools import chain
import numpy as np
import networkx as nx

h, w, *X = map(int, open(0).read().split())
C = np.array(X[:100], dtype=int).reshape((10, 10))
A = np.array(X[100:], dtype=int).reshape((h, w))

G = nx.DiGraph(C)
d = {-1:0}
for i in range(10):
    d[i] = nx.dijkstra_path_length(G, i, 1, weight='weight')
print(sum(d[a] for a in chain(*A)))

h,w=list(map(int, input().split()))
c=[list(map(int, input().split())) for _ in range(10)]
a=[list(map(int, input().split())) for _ in range(h)]

def warshall_floyd(adj_m):
    # _dist[i][j] : i から j への最短距離
    _dist=adj_m
    for _k in range(10):
        for _i in range(10):
            for _j in range(10):
                _dist[_i][_j] = min(_dist[_i][_j], _dist[_i][_k]+_dist[_k][_j])
    return _dist

dist=warshall_floyd(c)

ans=0
for i in range(h):
    for j in range(w):
        if a[i][j]!=-1:
            ans+=dist[a[i][j]][1]
print(ans)


H,W = list(map(int, input().split()))
cArray = [list(map(int, input().split())) for _ in range(10)]
Aarray = [list(map(int, input().split())) for _ in range(H)]

for k in range(10):
    for i in range(10):
        for j in range(10):
            cArray[i][j] = min(cArray[i][j], cArray[i][k] + cArray[k][j])

#print(cArray)

ans = 0
for i in Aarray:
    for j in i:
        if(j != -1):
            ans += cArray[j][1]

print(ans)

H,W=list(map(int,input().split()))
c=[list(map(int,input().split())) for i in range(10)]
A=[list(map(int,input().split())) for i in range(H)]

for k in range(10):
    for i in range(10):
        for j in range(10):
            c[i][j]=min(c[i][j],c[i][k]+c[k][j])
ans=0
for i in range(H):
    for j in range(W):
        if A[i][j]==-1:
            continue
        ans+=c[A[i][j]][1]
print(ans)


from collections import defaultdict
dicA = defaultdict(int) 

H,W = map(int,input().split())
C = []
min_step = []
for i in range(10):
  temp = list(map(int,input().split()))
  C.append(temp)
  min_step.append(temp[1])
#print(C)
#print(min_step)

def dfs(n,k,now): #0indexの数字nから1に行くのに最短の値。nowステップ進んで今kにいる。
  if now > min_step[n]:
    return
  for i in range(10):
    if i == 1: #kから0に行ったときは、現状の最短とどちらが近いかを比較。
      #print(min_step[n],now+ C[k][1])
      min_step[n] = min(min_step[n],now+ C[k][1])
    if i != k:
      if C[k][i]+now < min_step[n]: #iを経由しても現状の最短よりも近い。
        #print(n,i,now,C[k][i])
        dfs(n,i,C[k][i]+now)

for i in range(10):
  if i == 1:
    continue
  for j in range(10):
    if i!=j:
      dfs(i,j,C[i][j])

#print(min_step)

for i in range(H):
  temp = list(map(int,input().split()))
  for j in range(W):
    if temp[j] == -1:
      continue
    dicA[temp[j]] +=1 #数字を0indexに
ans = 0
#print(dicA)
for x in dicA.keys():
  ans += min_step[x]*dicA[x]
print(ans)

h, w = map(int, input().split())
c = [list(map(int, input().split())) for i in range(10)]

# Froyed-Warshal
for v in range(10):
    for s in range(10):
        for g in range(10):
            c[s][g] = min(c[s][g], c[s][v] + c[v][g])

a = [list(map(int, input().split())) for i in range(h)]

ans = 0
for i in range(h):
    for j in range(w):
        if a[i][j] == -1: continue
        ans += c[a[i][j]][1]
print(ans)

import math
from math import gcd,pi,sqrt
INF = float("inf")

import sys
sys.setrecursionlimit(10**6)
import itertools
from collections import Counter,deque
def i_input(): return int(input())
def i_map(): return list(map(int, input().split()))
def i_list(): return list(i_map())
def i_row(N): return [i_input() for _ in range(N)]
def i_row_list(N): return [i_list() for _ in range(N)]
def s_input(): return input()
def s_map(): return input().split()
def s_list(): return list(s_map())
def s_row(N): return [s_input for _ in range(N)]
def s_row_str(N): return [s_list() for _ in range(N)]
def s_row_list(N): return [list(s_input()) for _ in range(N)]

def main():
    h,w = i_map()
    c = [i_list() for i in range(10)]

    for k in range(10):
        for i in range(10):
            for j in range(10):
                c[i][j] = min(c[i][j], c[i][k] + c[k][j])

    ans = 0
    for h in range(h):
        a = i_list()
        for b in a:
            if b>=0:
                ans += c[b][1]
    print(ans)



def __starting_point():
    main()

__starting_point()

H,W=map(int,input().split())
c=[list(map(int,input().split())) for i in range(10)]
A=[list(map(int,input().split())) for i in range(H)]
 
for k in range(10):
    for i in range(10):
        for j in range(10):
            c[i][j]=min(c[i][j],c[i][k]+c[k][j])
ans=0
for i in range(H):
    for j in range(W):
        if A[i][j]==-1:
            continue
        ans+=c[A[i][j]][1]
print(ans)

h, w = list(map(int, input().split()))
c = [list(map(int, input().split())) for _ in range(10)]

visited = {}
dist = {}
for i in range(10):
    dist[i] = 100000
dist[1] = 0

while len(dist) > 0:
    cur, curDist = sorted(dist.items(), key=lambda x: x[1])[0]
    del dist[cur]
    visited[cur] = curDist

    for i in range(10):
        if i == cur or i in visited:
            continue

        newDist = curDist + c[i][cur]
        dist[i] = min(dist[i], newDist)

cnts = [0] * 10
for _ in range(h):
    a = list(map(int, input().split()))
    for ai in a:
        if ai != -1:
            cnts[ai] += 1

cnt = 0
for i in range(10):
    cnt += cnts[i]*visited[i]

print(cnt)

def main():
	H, W = [int(x) for x in input().split(" ")]
	C = []
	for i in range(10):
		c = [int(m) for m in input().split(" ")]
		C.append(c)
	A = [0] * 10 # 0 ~ 9, idx = 10 -> -1
	for i in range(H):
		a = [int(m) for m in input().split(" ")]
		for j in range(W):
			if a[j] != -1:
				A[a[j]] += 1

	MP = [[C[i][1] for i in range(10)]] # MP[0] -> overwrite once, MP[1] -> overwrite twice
	for i in range(9):
		MP.append([min([(C[k][j] + MP[-1][j]) for j in range(10)]) for k in range(10)])

	minMP = [10000] * 10
	for i in range(len(MP)):
		for j in range(len(MP[i])):
			minMP[j] = min([minMP[j], MP[i][j]])
	print(sum([p * q for (p, q) in zip(A, minMP)]))

main()

h, _ = map(int, input().split())

r = range(10)
c = [[int(i) for i in input().split()] for _ in r]

for k in r:
    for i in r:
        for j in r:
            c[i][j] = min(c[i][j], c[i][k] + c[k][j])
else:
    a = [[int(i) for i in input().split()] for _ in range(h)]
    print(sum(c[i][1] for i in sum(a, []) if i != -1))

def warshall_floyd(V):
    for k in range(V):
        for i in range(V):
            for j in range(V):
                d[i][j] = min(d[i][j], d[i][k] + d[k][j])

                
from collections import Counter

INF = float('inf') 
H, W = list(map(int, input().split()))
d =[[int(i) for i in input().split()] for _ in range(10)]  #; print(d)
a = []
for _ in range(H):
    a.extend([int(i) for i in input().split() if i != '-1'])
dic = Counter(a)     #; print(a); print(dic) 

warshall_floyd(10)   #; print(d)

ans = 0
for key, val in list(dic.items()):
    ans += d[key][1] * val   #; print(key, d[key][1], val)

print(ans)


H, W = list(map(int, input().split()))
C = [list(map(int, input().split())) for _ in range(10)]
for i in range(10):
    for k in range(10):
        for l in range(10):
            C[k][l] = min(C[k][l], C[k][i]+C[i][l])
ans = 0
"""
for _ in C:
    print(_)
"""
for i in range(H):
    A = list(map(int,input().split()))
    for j in A:
        if j != -1:
            ans += C[j][1]
print(ans)


import sys
read = sys.stdin.read
from collections import Counter
def main():
    def warshall_floyd(d):
        for k in range(n):
            for i in range(n):
                for j in range(n):
                    d[i][j] = min(d[i][j], d[i][k] + d[k][j])
        return d

    h, w = list(map(int, input().split()))
    n = 10
    d = []
    for _ in range(10):
        d.append(list(map(int, input().split())))
    d = warshall_floyd(d)
    a = []
    for _ in range(h):
        row = list(map(int, input().split()))
        row = [1 if i == -1 else i for i in row]
        a.extend(row)
    aa = Counter(a)
    ans = 0
    for i0 in range(10):
        ans += aa[i0] * d[i0][1]
    print(ans)
def __starting_point():
    main()

__starting_point()

H, W = list(map(int, input().split()))
c = [list(map(int, input().split())) for _ in range(10)]
A = [list(map(int, input().split())) for _ in range(H)]


# Warshall–Floyd
def main():
    for k in range(10):
        for i in range(10):
            for j in range(10):
                c[i][j] = min(c[i][j], c[i][k] + c[k][j])

    print((
        sum(
            c[a][1] for column in A for a in column if a >= 0 
        )
    ))


def __starting_point():
    main()


__starting_point()

H, W = list(map(int, input().split()))
cost = [list(map(int, input().split())) for i in range(10)]
A = [list(map(int, input().split())) for i in range(H)]

for k in range(10):
    for i in range(10):
        for j in range(10):
            cost[i][j] = min(cost[i][j], cost[i][k] + cost[k][j])
            
ans = 0
for i in range(H):
    for j in range(W):
        now = A[i][j]
        if now != -1:
            ans += cost[now][1]
            
print(ans)


from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson, csgraph_from_dense

H, W = [int(x) for x in input().split()]
C = [[int(x) for x in input().split()] for _ in range(10)]
A = [[int(x) for x in input().split()] for _ in range(H)]


G = csgraph_from_dense(C, null_value=0)

d = floyd_warshall(G)

ans = 0

for i in range(H):
    for j in range(W):
        if A[i][j] == 1 or A[i][j] == -1:
            continue
        ans += d[A[i][j]][1]


print((int(ans)))




import sys
readline = sys.stdin.readline

H,W = map(int,readline().split())
C = [None] * 10
for i in range(10):
  C[i] = list(map(int,readline().split()))

for k in range(10):
  for i in range(10):
    for j in range(10):
      C[i][j] = min(C[i][j], C[i][k] + C[k][j])

from collections import defaultdict
wall = defaultdict(int)
for i in range(H):
  for w in list(map(int,readline().split())):
    wall[w] += 1
  
ans = 0
for key,value in wall.items():
  if key == -1:
    continue
  ans += value * C[key][1]
  
print(ans)

INF=float('inf')
h,w=map(int,input().split())
dist=[[0 for i in range(10)]for j in range(10)]
for i in range(10):
  s=list(map(int,input().split()))
  for j in range(10):
    if i==j:
      continue
    dist[i][j]=s[j]

for k in range(10):
  for i in range(10):
    for j in range(10):
      dist[i][j]=min(dist[i][j],dist[i][k]+dist[k][j])
ans=0
for i in range(h):
  T=list(map(int,input().split()))
  for j in range(w):
    if T[j]==-1:
      continue
    if T[j]==1:
      continue
    ans+=dist[T[j]][1]
print(ans)

#!/usr/bin/env python3
import sys

def solve(H: int, W: int, c: "List[List[int]]", A: "List[List[int]]"):
    import numpy as np
    from scipy.sparse.csgraph import floyd_warshall
    from itertools import chain
    mat = floyd_warshall(np.array(c, dtype=np.int64), directed=True)    
    return int(sum(mat[a][1] for a in [x for x in chain.from_iterable(A) if x >= 0]))

# Generated by 1.1.6 https://github.com/kyuridenamida/atcoder-tools
def main():
    def iterate_tokens():
        for line in sys.stdin:
            for word in line.split():
                yield word
    tokens = iterate_tokens()
    H = int(next(tokens))  # type: int
    W = int(next(tokens))  # type: int
    c = [[int(next(tokens)) for _ in range(9 - 0 + 1)] for _ in range(9 - 0 + 1)]  # type: "List[List[int]]"
    A = [[int(next(tokens)) for _ in range(W)] for _ in range(H)]  # type: "List[List[int]]"
    print((solve(H, W, c, A)))

def test():
    import doctest
    doctest.testmod()

def __starting_point():
    #test()
    main()

__starting_point()

H, W = map(int, input().split())
C = [list(map(int, input().split())) for _ in range(10)]

cost = [99999]*10
cost[1] = 0

def f(n):
    for i in range(10):
        flag = False
        cc = C[i][n]+cost[n]
        if cc < cost[i]:
            flag = True
            cost[i] = cc
            f(i)

f(1)

ans = 0
for _ in range(H):
    for n in map(int, input().split()):
        if n < 0:
            continue
        ans += cost[n]

print(ans)

# -*- coding: utf-8 -*-


def warshall_floyd(dist):
    v_count = len(dist[0])

    for k in range(v_count):
        for i in range(v_count):
            for j in range(v_count):
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

    return dist


def main():
    h, w = list(map(int, input().split()))
    c = [list(map(int, input().split())) for _ in range(10)]
    a = [list(map(int, input().split())) for _ in range(h)]
    ans = 0

    results = warshall_floyd(c)

    for i in range(h):
        for j in range(w):
            if a[i][j] != -1:
                ai = a[i][j]
                ans += results[ai][1]

    print(ans)


def __starting_point():
    main()

__starting_point()

H, W = map(int, input().split())
C = []
N = 10
for i in range(N):
    c = list(map(int, input().split()))
    C.append(c)

def w_f(C):
    for k in range(N):
        for i in range(N):
            for j in range(N):
                C[i][j] = min(C[i][j], C[i][k]+C[k][j])
    return C

C = w_f(C)

A = []
for i in range(H):
    a = list(map(int, input().split()))
    A.append(a)

ans = 0
for h in range(H):
    for w in range(W):
        if A[h][w] != -1:
            ans += C[A[h][w]][1]
            
print(ans)

H,W=map(int,input().split())

arr=[list(map(int,input().split())) for i in range(10)]
wall=[list(map(int,input().split())) for i in range(H)]


for i in range(10):
    for j in range(10):
        for k in range(10):
            arr[j][k]=min(arr[j][i]+arr[i][k],arr[j][k])

ans = 0
for i in range(H):
    for item in wall[i]:
        if item<0:
            continue
        ans += arr[item][1]  
print(ans)

h,w = list(map(int,input().split()))
n=10
dist = [list(map(int,input().split())) for _ in range(n)]
wall = [list(map(int,input().split())) for _ in range(h)]

for k in range(n):
    for i in range(n):
        for j in range(n):
            dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])
#[print(*dist[l]) for l in range(n)]
ans = 0
for i in range(h):
    for j in range(w):
        if wall[i][j]!=-1:
            ans += dist[wall[i][j]][1]
print(ans)



def main():
    import sys
    from heapq import heappop, heappush

    def input(): return sys.stdin.readline().rstrip()

    def dijkstra(s):
        inf = 10**6
        dist = [inf]*10
        dist[1] = 0
        que = [(0, 1)]
        while que:
            cost, node = heappop(que)
            if cost > dist[node]:
                continue
            for i in range(10):
                if i == node:
                    continue
                if dist[i] > dist[node] + g[i][node]:
                    dist[i] = dist[node]+g[i][node]
                    heappush(que, (dist[i], i))
        return dist
    
    h, w = map(int, input().split())
    g = [[] for _ in range(10)]
    for i in range(10):
        g[i] = list(map(int, input().split()))

    from collections import defaultdict
    c_lis = defaultdict(int)
    for i in range(h):
        for j in input().split():
            tmp = int(j)
            if abs(tmp) != 1:
                c_lis[tmp] += 1
    
    dist = dijkstra(1)
    ans = 0
    for key in c_lis:
        ans += c_lis[key]*dist[key]
    print(ans)



def __starting_point():
    main()
__starting_point()

H, W = map(int, input().split())
C = []
for i in range(10):
  c = list(map(int, input().split()))
  C.append(c)
A = []
for i in range(H):
  a = list(map(int, input().split()))
  A.append(a)
  
for k in range(10):
  for i in range(10):
    for j in range(10):
      if C[i][k]+C[k][j] < C[i][j]:
        C[i][j] = C[i][k] + C[k][j]
        
ans = 0
for i in range(H):
  l = A[i]
  for j in range(W):
    n = l[j]
    if (n==0) or (n>1):
      ans += C[n][1]
print(ans)

h,w=map(int,input().split())
c=[list(map(int,input().split())) for _ in range(10)]
a=[list(map(int,input().split())) for _ in range(h)]

dist=[]
dist.extend(c)
for i in range(10):
  for j in range(10):
    for k in range(10):
      if dist[j][k]>dist[j][i]+dist[i][k]:
        dist[j][k]=dist[j][i]+dist[i][k]
print(sum(dist[a[i][j]][1] for i in range(h) for j in range(w) if a[i][j]>-1))

#!/usr/bin/env python3
import copy
from itertools import product
import sys
# from pprint import pprint
sys.setrecursionlimit(10**6)

h, w = list(map(int, input().split()))
map_ = [list(map(int, input().split())) for i in range(10)]

min_ = [[10**4]*10 for i in range(10)]


# dq = [0, 0, set([0])]


# while(dq):
#     num, value, lists = dq.pop()
#     for i in range(10):
#         if i == 1:


def dfs(start=0, now=0, value=0):
    for i in range(10):
        value_tmp = value+map_[now][i]
        if value_tmp < min_[start][i]:
            min_[start][i] = value_tmp
            dfs(start, now=i, value=value_tmp)


for i in range(10):
    dfs(start=i, now=i, value=0)

count = [0]*10
for i in range(h):
    tmp = list(map(int, input().split()))
    for i in tmp:
        if i != -1:
            count[i] += 1

ans = 0
for i in range(10):
    ans += min_[i][1]*count[i]
print(ans)


N = 10
MAX_C = 1000


H, W = [int(x) for x in input().split()]
C = [[int(x) for x in input().split()] for _ in range(N)]
dist = [0 if i == 1 else MAX_C for i in range(N)]


def bellman_ford():
    for _ in range(N - 1):
        for u in range(N):
            for v in range(N):
                dist[v] = min(dist[v], dist[u] + C[v][u])


bellman_ford()
ans = sum([sum([0 if x == "-1" else dist[int(x)] for x in input().split()]) for _ in range(H)])
print(ans)


#!/usr/bin/env python
# coding: utf-8

# In[1]:


H,W = list(map(int, input().split()))
c = []
for _ in range(10):
    c.append(list(map(int, input().split())))
A = []
for _ in range(H):
    A.append(list(map(int, input().split())))


# In[3]:


def wf_func(mat):
    dist = mat
    for k in range(10):
        for i in range(10):
            for j in range(10):
                dist[i][j] = min(dist[i][j], dist[i][k]+dist[k][j])
    return dist


# In[5]:


dist = wf_func(c)
ans = 0
for i in range(H):
    for j in range(W):
        if A[i][j] != -1:
            ans += dist[A[i][j]][1]
print(ans)


# In[ ]:






#http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=GRL_1_C&lang=ja
#https://dai1741.github.io/maximum-algo-2012/docs/shortest-path/

INF = (2*10**7)*100 + 1234567 #十分大きい値にすること!!!!!!

H,W = map(int, input().split())
c = [[int(e) for e in input().split()] for i in range(10)]

#Warshall–Floydで1に変える魔力を求めておく
for k in range(10):
    for i in range(10):
        for j in range(10):
            if c[i][j] > c[i][k] + c[k][j] and c[i][k]!=INF and c[k][j]!=INF:
                c[i][j] = c[i][k] + c[k][j]

ans = 0
for i in range(H):
    A_row = [int(e) for e in input().split()]
    for A in A_row:
        if A != -1:
            ans += c[A][1]
            
print(ans)

import sys

def warshall_floyd():
    for k in range(10):
        for i in range(10):
            for j in range(10):
                C[i][j] = min(C[i][j], C[i][k] + C[k][j])

H, W = list(map(int, input().split()))
inf = float("inf")
C = [list(map(int, sys.stdin.readline().rsplit())) for _ in range(10)]
A = [list(map(int, sys.stdin.readline().rsplit())) for _ in range(H)]
warshall_floyd()
res = 0
for row in A:
    for col in row:
        if col != -1:
            res += C[col][1]

print(res)


from numpy import *
from scipy.sparse.csgraph import *
H,W = map(int,input().split())
G = array([list(map(int,input().split())) for n in range(10)])
A = [list(map(int,input().split())) for h in range(H)]
F = shortest_path(G)
ans = 0

for h in range(H):
  for w in range(W):
    if A[h][w]!=-1:
      ans+=F[A[h][w]][1]

print(int(ans))

import sys
readline = sys.stdin.readline

H,W = map(int,readline().split())
C = [None] * 10
for i in range(10):
  C[i] = list(map(int,readline().split()))

for k in range(10):
  for i in range(10):
    for j in range(10):
      C[i][j] = min(C[i][j], C[i][k] + C[k][j])
      
ans = 0
for i in range(H):
  line = list(map(int,readline().split()))
  for j in range(len(line)):
    if line[j] == -1:
      continue
    ans += C[line[j]][1]
    
print(ans)

from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix

h, w = map(int, input().split())
ma = [ list(map(int,input().split(" "))) for i in range(10)]
sco = [ list(map(int,input().split(" "))) for i in range(h)]
a = csr_matrix(ma)
b = dijkstra(a)
ans = 0
for i in range(h):
  for j in range(w):
    num = sco[i][j]
    if num != -1:
      ans += b[num][1]
print(int(ans))

import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time, copy,bisect
from operator import itemgetter
from heapq import heappush, heappop
import numpy as np
from scipy.sparse.csgraph import shortest_path, floyd_warshall, dijkstra, bellman_ford, johnson
from scipy.sparse import csr_matrix

sys.setrecursionlimit(10**7)
inf = 10**20
mod = 10**9 + 7

stdin = sys.stdin

ni = lambda: int(ns())
nf = lambda: float(ns())
na = lambda: list(map(int, stdin.readline().split()))
nb = lambda: list(map(float, stdin.readline().split()))
ns = lambda: stdin.readline().rstrip()  # ignore trailing spaces


H, W = na()
c = [na() for _ in range(10)]
A = [na() for _ in range(H)]
adj = [[] for _ in range(10)]



# cost[i][j]: 頂点v_iから頂点v_jへ到達するための辺コストの和
for k in range(10):
    for i in range(10):
        for j in range(10):
            c[i][j] = min(c[i][j], c[i][k] + c[k][j])
ans = 0
for y in range(H):
    for x in range(W):
        if A[y][x] != -1:
            #print(ans)
            ans += c[A[y][x]][1]
print(ans)



import sys
import math
import itertools
import bisect
from copy import copy
from collections import deque,Counter
from decimal import Decimal
def s(): return input()
def i(): return int(input())
def S(): return input().split()
def I(): return map(int,input().split())
def L(): return list(input().split())
def l(): return list(map(int,input().split()))
def lcm(a,b): return a*b//math.gcd(a,b)
sys.setrecursionlimit(10 ** 9)
INF = 10**9
mod = 10**9+7

H,W = I()
cost = [l() for _ in range(10)]
A = [l() for _ in range(H)]
ans = 0
for k in range(10):
    for i in range(10):
        for j in range(10):
            cost[i][j] = min(cost[i][j], cost[i][k] + cost[k][j])
for i in range(H):
    for j in range(W):
        if A[i][j] > -1:
            ans += cost[A[i][j]][1]
print(ans)

from collections import Counter
from scipy.sparse.csgraph import floyd_warshall

H, W = list(map(int, input().split()))
C = [list(map(int, input().split())) for _ in range(10)]
A = [list(map(int, input().split())) for _ in range(H)]


num_counter = Counter()
for i in range(H):
    num_counter += Counter(A[i])

if -1 in num_counter:
    del num_counter[-1]

if 1 in num_counter:
    del num_counter[1]

nei_graph = floyd_warshall(C, directed=True)

ans = 0
for k, v in list(num_counter.items()):
    ans += nei_graph[k][1] * v

print((int(ans)))



h, w = list(map(int, input().split()))

g = []
for _ in range(10):
    a = list(map(int, input().split()))
    g.append(a)

for k in range(10):
    for i in range(10):
        for j in range(10):
            g[i][j] = min(g[i][j], g[i][k] + g[k][j])

ans = 0
for i in range(h):
    ans += sum([g[x][1] for x in [x for x in map(int, input().split()) if x != -1]])
print(ans)


H, W = map(int, input().split())
C = [list(map(int, input().split())) for _ in range(10)]
A = [list(map(int, input().split())) for _ in range(H)]

for k in range(10):
    for i in range(10):
        for j in range(10):
            C[i][j] = min(C[i][j], C[i][k] + C[k][j])

answer = 0
for i in range(H):
    for j in range(W):
        if A[i][j] == -1:
            continue
        answer += C[A[i][j]][1]

print(answer)

from math import ceil,floor,factorial,gcd,sqrt,log2,cos,sin,tan,acos,asin,atan,degrees,radians,pi,inf,comb
from itertools import accumulate,groupby,permutations,combinations,product,combinations_with_replacement
from collections import deque,defaultdict,Counter
from bisect import bisect_left,bisect_right
from operator import itemgetter
from heapq import heapify,heappop,heappush
from queue import Queue,LifoQueue,PriorityQueue
from copy import deepcopy
from time import time
from functools import reduce
import string
import sys
sys.setrecursionlimit(10 ** 7)
def input() : return sys.stdin.readline().strip()
def INT()   : return int(input())
def MAP()   : return map(int,input().split())
def LIST()  : return list(MAP())

h, w = MAP()
c = []
for i in range(10):
    c.append(LIST())
a = []
for i in range(h):
    a.append(LIST())

for i in range(10):
    for j in range(10):
        for k in range(10):
            c[j][k] = min(c[j][k], c[j][i]+c[i][k])

ans = 0
for i in range(h):
    for j in range(w):
        if a[i][j] != -1:
            ans += c[a[i][j]][1]
print(ans)

# -*- coding: utf-8 -*-


def warshall_floyd(dist):
    v_count = len(dist[0])

    for k in range(v_count):
        for i in range(v_count):
            for j in range(v_count):
                dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j])

    return dist


def main():
    h, w = list(map(int, input().split()))
    c = [list(map(int, input().split())) for _ in range(10)]
    a = [list(map(int, input().split())) for _ in range(h)]
    ans = 0

    results = warshall_floyd(c)

    for i in range(h):
        for j in range(w):
            if a[i][j] != -1:
                ai = a[i][j]
                ans += results[ai][1]

    print(ans)


def __starting_point():
    main()

__starting_point()

H,W=map(int,input().split())
C=[list(map(int,input().split())) for _ in range(10)]
d=[0]*10
for _ in range(H):
  for i in list(map(int,input().split())):
    if i>=0: d[i]+=1
r=range(10)
for k in r:
  for i in r:
    for j in r:
      C[i][j]=min(C[i][j],C[i][k]+C[k][j])

print(sum(C[i][1]*d[i] for i in r))

def main():
    from sys import stdin
    def input():
        return stdin.readline().strip()

    h, w = map(int, input().split())
    c = [[int(i) for i in input().split()] for _ in range(10)]
    a = [[int(i) for i in input().split()] for _ in range(h)]

    # Warshall-Floyd
    for k in range(10):
        for i in range(10):
            for j in range(10):
                if c[i][j] > c[i][k] + c[k][j]:
                    c[i][j] = c[i][k] + c[k][j]

    ans = 0
    for i in a:
        for j in i:
            if j == -1:
                continue
            else:
                ans += c[j][1]

    print(ans)

main()

H, W = list(map(int, input().split()))
C = []
for _ in range(10):
    c = list(map(int, input().split()))
    C.append(c)

A = []
for _ in range(H):
    a = list(map(int, input().split()))
    A.append(a)

# 0-9を1に変える時の最小のエネルギーをそれぞれ求める(ワーシャルフロイド法)
for k in range(10):
    for i in range(10):
        for j in range(10):
            C[i][j] = min(C[i][j], C[i][k] + C[k][j])

count = 0
for i in range(H):
    for j in range(W):
        if (A[i][j] == -1):
            continue
        else:
            count += C[A[i][j]][1]

print(count)


#!/usr/bin/env python3
h, w = list(map(int, input().split()))
c = [[*list(map(int, input().split()))] for _ in range(10)]
a = [[*list(map(int, input().split()))] for _ in range(h)]
d = [c[i][1] for i in range(10)]
for i in range(10):
    for j in range(10):
        d[j] = min(d[j], min(c[j][k] + d[k] for k in range(10)))
d += [0]
print((sum(d[i] for i in sum(a,[]))))


def Wall():
    h, w = list(map(int, input().split()))

    # Warshall Floyd配列
    wf = [list(map(int, input().split())) for _ in range(10)]

    # Warshall Floyd初期値代入
    for i in range(10):
        wf[i][i] = 0

    # Warshall Floyd
    for i in range(10):
        for j in range(10):
            for k in range(10):
                wf[j][k] = min(wf[j][i]+wf[i][k], wf[j][k])
    ans = 0
    for _ in range(h):
        a = list(map(int, input().split()))
        for v in a:
            if v == -1:
                continue
            ans += wf[v][1]
    print(ans)

def __starting_point():
    Wall()
    

__starting_point()