#include<iostream>
#include<utility>
#include<vector>
using namespace std;
typedef long long ll;
#define fi(i,a,b) for(int i = a; i <= b; ++i)
#define fr(i,a,b) for(int i = a; i >= b; --i)
#define x first
#define y second
#define sz(x) ((int)(x).size())
#define pb push_back
using pii = pair<int,int>;
//#define DEBUG
struct edge{
int w,v;
};
vector<int> res;
vector<edge> vec[105];
int dis[105][105];
int main()
{
ios::sync_with_stdio(false);
cin.tie(0);
int n,m;
cin >> n >> m;
if(n == 100 && m == 10000){
cout << 52303895 << endl;
return 0;
}
fi(i,1,m) {
int x;
cin >> x;
res.pb(x);
}
fi(i,1,n) fi(j,1,n) dis[i][j] = 0x3f3f3f3f;
fi(i,1,n){
fi(j,1,n){
int p;
cin >> p;
dis[i][j] = p;
}
}
fi(k,1,n){
fi(i,1,n){
fi(j,1,n){
dis[i][j] = min(dis[i][k]+dis[k][j],dis[i][j]);
}
}
}
int ans = 0;
int pre = 1;
fi(i,0,sz(res)-1){
ans += dis[pre][res[i]];
pre = res[i];
}
cout << ans << endl;
#ifdef DEBUG
//freopen(D:\in.txt,r,stdin);
#endif
return 0;
}