#include <bits/stdc++.h>
using namespace std;
long long max(long long a, long long b) { return a > b ? a : b; }
long long min(long long a, long long b) { return a < b ? a : b; }
const long long INF = 1e9 + 7;
vector<vector<long long> > adj, dp;
vector<long long> in;
long long n;
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cin >> n;
  adj.resize(n, vector<long long>(n, 0));
  dp.resize(n, vector<long long>(n, 0));
  in.resize(n, 0);
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < n; j++) {
      cin >> adj[i][j];
    }
  }
  for (long long i = 0; i < n; i++) cin >> in[i], in[i]--;
  long long ctr = 0;
  vector<long long> sol;
  for (long long k = n - 1; k >= 0; k--) {
    for (long long i = n - 1; i >= 0; i--) {
      for (long long j = n - 1; j >= 0; j--) {
        if (adj[in[i]][in[j]] > adj[in[i]][in[k]] + adj[in[k]][in[j]]) {
          adj[in[i]][in[j]] = adj[in[i]][in[k]] + adj[in[k]][in[j]];
        }
        if (i >= k && j >= k) {
          ctr += adj[in[i]][in[j]] - dp[in[i]][in[j]];
          dp[in[i]][in[j]] = adj[in[i]][in[j]];
        }
      }
    }
    sol.push_back(ctr);
  }
  for (long long i = n - 1; i >= 0; i--) cout << sol[i] << " ";
  cout << "\n";
}
