#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
char buf[10000000], *ptr = buf - 1;
inline int readint(){
int n = 0;
char ch = *++ptr;
while(ch < ‘0‘ || ch > ‘9‘) ch = *++ptr;
while(ch <= ‘9‘ && ch >= ‘0‘){
n = (n << 1) + (n << 3) + ch - ‘0‘;
ch = *++ptr;
}
return n;
}
const int maxn = 100 + 10, maxm = 10000 + 10;
int f[maxn][maxn], a[maxm];
int main(){
fread(buf, sizeof(char), sizeof(buf), stdin);
int N, M;
N = readint();
M = readint();
for(int i = 1; i <= M; i++) a[i] = readint();
for(int i = 1; i <= N; i++)
for(int j = 1; j <= N; j++)
f[i][j] = readint();
for(int k = 1; k <= N; k++)
for(int i = 1; i <= N; i++)
for(int j = 1; j <= N; j++)
f[i][j] = min(f[i][j], f[i][k] + f[k][j]);
long long ans = 0;
for(int i = 2; i <= M; i++) ans += f[a[i - 1]][a[i]];
printf("%lld\n", ans);
return 0;
};