#include <bits/stdc++.h>
using namespace std;
long long e[1000][1000], v[1000], dist[1000][1000];
vector<long long> ans;
int main() {
  ios::sync_with_stdio(0);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++)
    for (int j = 1; j <= n; j++) {
      cin >> e[j][i];
      dist[j][i] = e[j][i];
    }
  for (int i = 1; i <= n; i++) cin >> v[i];
  reverse(&v[1], &v[n + 1]);
  for (int i = 1; i <= n; i++) {
    for (int j = 1; j <= n; j++)
      for (int k = 1; k <= n; k++)
        dist[j][k] = min(dist[j][k], dist[j][v[i]] + dist[v[i]][k]);
    ans.push_back(0);
    for (int j = 1; j <= i; j++)
      for (int k = 1; k <= i; k++) ans.back() += dist[v[j]][v[k]];
  }
  reverse(ans.begin(), ans.end());
  for (int i = 0; i < ans.size(); i++) cout << ans[i] << endl;
}
