#include <bits/stdc++.h>
using namespace std;
const long long INF = 1e12;
int n;
int edge[505][505];
vector<int> ts;
vector<long long> ans;
long long d[505][505];
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cout.tie(nullptr);
  ;
  cin >> n;
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      int c;
      cin >> c;
      edge[i][j] = c;
    }
  }
  ts.resize(n);
  ans.resize(n);
  for (int i = n - 1; i >= 0; i--) {
    int t;
    cin >> t;
    t--;
    ts[i] = t;
  }
  for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
      d[i][j] = edge[i][j];
    }
  }
  for (int ki = 0; ki < n; ki++) {
    int k = ts[ki];
    for (int i = 0; i < n; i++) {
      for (int j = 0; j < n; j++) {
        d[ts[i]][ts[j]] = min(d[ts[i]][ts[j]], d[ts[i]][k] + d[k][ts[j]]);
      }
    }
    long long pa = 0;
    for (int i = 0; i <= ki; i++) {
      for (int j = 0; j <= ki; j++) {
        if (d[ts[i]][ts[j]] != INF) pa += d[ts[i]][ts[j]];
      }
    }
    ans[ans.size() - 1 - ki] = pa;
  }
  for (long long t : ans) cout << t << " ";
  cout << "\n";
}
