#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e18;
const int32_t M = 1e9 + 7;
const int32_t MM = 998244353;
long long dis[501][501];
long long newdis[501][501];
long long newdis2[501][501];
void shiftrow(long long n, vector<long long> v) {
  for (long long i = 1; i < n + 1; ++i) {
    for (long long j = 1; j < n + 1; ++j) {
      newdis[i][j] = dis[v[i - 1]][j];
    }
  }
}
void shiftcol(long long n, vector<long long> v) {
  for (long long j = 1; j < n + 1; ++j) {
    for (long long i = 1; i < n + 1; ++i) {
      newdis2[i][j] = newdis[i][v[j - 1]];
    }
  }
}
void solve() {
  long long n;
  cin >> n;
  for (long long i = 1; i < n + 1; ++i) {
    for (long long j = 1; j < n + 1; ++j) {
      cin >> dis[i][j];
    }
  }
  vector<long long> rem(n + 1);
  for (long long i = 1; i < n + 1; ++i) cin >> rem[i];
  reverse(rem.begin(), rem.end());
  shiftrow(n, rem);
  shiftcol(n, rem);
  vector<long long> ans;
  for (long long k = 1; k <= n; k++) {
    for (long long i = 1; i <= n; i++) {
      for (long long j = 1; j <= n; j++) {
        newdis2[i][j] = min(newdis2[i][j], newdis2[i][k] + newdis2[k][j]);
      }
    }
    long long sum = 0;
    for (long long i = 1; i <= k; i++) {
      for (long long j = 1; j <= k; j++) {
        sum += newdis2[i][j];
      }
    }
    ans.push_back(sum);
  }
  reverse(ans.begin(), ans.end());
  for (long long i = 0; i < n; ++i) cout << ans[i] << " ";
  cout << endl;
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  for (long long i = 0; i < 501; ++i) {
    for (long long j = 0; j < 501; ++j) {
      dis[i][j] = 0;
      newdis[i][j] = 0;
      newdis2[i][j] = 0;
    }
  }
  solve();
  return 0;
}
