#include <bits/stdc++.h>
using namespace std;
const int maxn=1e6+10;
const int inf=0x3f3f3f3f;
struct edge{
int z,y,nxt,w;
}e[maxn];
int head[maxn],n,m,tot=0;
struct node{
int x,d;
bool operator<(const node A)const{
return d>A.d;
}
};
void add(int x,int y,int z){
e[++tot]=(edge){x,y,head[x],z};
head[x]=tot;
}
int dis[maxn];
bool vis[maxn];
priority_queue<node>q;
int dijkstra(int s,int a){
memset(dis,inf,sizeof(dis));
memset(vis,0,sizeof(vis));
dis[s]=0;
q.push(node{s,0});
while(!q.empty()){
int now=q.top().x;
q.pop();
if(vis[now])continue;
vis[now]=1;
for(int i=head[now];~i;i=e[i].nxt){
int to=e[i].y;
if(vis[to])continue;
if(!vis[to]&&dis[to]>dis[now]+e[i].w){
dis[to]=dis[now]+e[i].w;
q.push((node){to,dis[to]});
}
}
}
return dis[a];
}
int main(){
memset(head,-1,sizeof(head));
cin >> n >> m;
int num[maxn];
for(int i=1;i<=m;i++){
cin >> num[i];
}
int map[1000][1000];
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
cin >> map[i][j];
}
}
for(int i=1;i<=n;i++){
for(int j=1;j<=n;j++){
if(map[i][j]!=0){
add(i,j,map[i][j]);
}
}
}
int ans=0;
for(int i=1;i<m;i++){
ans+=dijkstra(num[i],num[i+1]);
}
cout << ans << endl;
return 0;
}