#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
long long power(long long a, long long b) {
  if (b == 0) return 1;
  long long res = power(a, b / 2);
  long long ans = res * res;
  ans %= mod;
  if (b % 2 == 0) return ans;
  return (a * ans) % mod;
}
bool sortbysec(const pair<int, int> &a, const pair<int, int> &b) {
  return (a.second < b.second);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long n;
  cin >> n;
  vector<vector<long long>> v(n, vector<long long>(n));
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) cin >> v[i][j];
  }
  vector<long long> x(n), ans(n);
  for (long long k = 0; k < n; k++) {
    cin >> x[k];
    x[k]--;
  }
  reverse(x.begin(), x.end());
  long long dist[n][n];
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) dist[i][j] = INT_MAX;
  }
  for (long long k = 0; k < n; k++) {
    for (int i = 0; i < k + 1; i++) {
      for (int j = 0; j < k + 1; j++)
        dist[x[i]][x[j]] = min(dist[x[i]][x[j]], v[x[i]][x[j]]);
    }
    for (int i = 0; i < k + 1; i++) {
      for (int j = 0; j < k + 1; j++) {
        dist[x[k]][x[j]] =
            min(dist[x[k]][x[j]], dist[x[k]][x[i]] + dist[x[i]][x[j]]);
        dist[x[j]][x[k]] =
            min(dist[x[j]][x[k]], dist[x[j]][x[i]] + dist[x[i]][x[k]]);
      }
    }
    for (int i = 0; i < k + 1; i++) {
      for (int j = 0; j < k + 1; j++) {
        dist[x[i]][x[j]] =
            min(dist[x[i]][x[j]], dist[x[i]][x[k]] + dist[x[k]][x[j]]);
      }
    }
    long long aa = 0;
    for (int i = 0; i < k + 1; i++) {
      for (int j = 0; j < k + 1; j++) {
        aa += dist[x[i]][x[j]];
      }
    }
    ans[k] = aa;
  }
  for (long long j = n - 1; j >= 0; j--) {
    cout << ans[j] << " ";
  }
  return 0;
}
