#include <bits/stdc++.h>
using namespace std;
signed main() {
  long long n;
  cin >> n;
  vector<vector<long long>> a(n, vector<long long>(n));
  for (long long i = 0; i < n; ++i) {
    for (long long j = 0; j < n; ++j) {
      cin >> a[i][j];
    }
  }
  vector<vector<long long>> f(n, vector<long long>(n, -1));
  vector<long long> z(n), ans(n);
  for (long long i = 0; i < n; ++i) {
    cin >> z[i];
    --z[i];
  }
  vector<bool> now(n);
  for (long long i = 0; i < n; ++i) {
    f[i][i] = 0;
  }
  for (long long i = n - 1; i >= 0; --i) {
    now[z[i]] = true;
    for (long long j = 0; j < n; ++j) {
      if (f[z[i]][j] == -1 || f[z[i]][j] > a[z[i]][j]) f[z[i]][j] = a[z[i]][j];
      if (f[j][z[i]] == -1 || f[j][z[i]] > a[j][z[i]]) f[j][z[i]] = a[j][z[i]];
    }
    for (long long j = 0; j < n; ++j) {
      for (long long k = 0; k < n; ++k) {
        if (f[j][z[i]] != -1 && f[z[i]][k] != -1 &&
            (f[j][k] == -1 || f[j][k] > f[j][z[i]] + f[z[i]][k])) {
          f[j][k] = f[j][z[i]] + f[z[i]][k];
        }
      }
    }
    long long sum = 0;
    for (long long j = 0; j < n; ++j) {
      for (long long k = 0; k < n; ++k) {
        if (f[j][k] != -1 && now[j] && now[k]) sum += f[j][k];
      }
    }
    ans[i] = sum;
  }
  for (long long i : ans) cout << i << " ";
}
