#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("unroll-loops")
#pragma GCC target("sse,sse2,sse3,ssse3,sse4,popcnt,abm,mmx,avx,tune=native")
using namespace std;
using ll = long long;
const int MAXN = 512;
int N;
ll A0[MAXN][MAXN], A[MAXN][MAXN];
int D[MAXN];
vector<ll> Ans;
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int N;
  cin >> N;
  for (int i = 0; i < int(N); i++)
    for (int j = 0; j < int(N); j++) cin >> A0[i][j];
  for (int i = 0; i < int(N); i++) cin >> D[i], --D[i];
  reverse(D, D + N);
  for (int i = 0; i < int(N); i++)
    for (int j = 0; j < int(N); j++) A[i][j] = A0[D[i]][D[j]];
  for (int k = 0; k < int(N); k++) {
    for (int i = 0; i < int(N); i++)
      for (int j = 0; j < int(N); j++)
        A[i][j] = min(A[i][j], A[i][k] + A[k][j]);
    ll sum = 0;
    for (int i = 0; i < int(k + 1); i++)
      for (int j = 0; j < int(k + 1); j++) sum += A[i][j];
    Ans.push_back(sum);
  }
  for (int i = Ans.size() - 1; i >= 0; --i) cout << Ans[i] << ' ';
  cout << endl;
  return 0;
}
