#include <bits/stdc++.h>
using namespace std;
const int INF = (-1u) / 2;
const long long int INF2 = (-1ull) / 2;
int a, b, i, d[510][510], j, k, n, m, timer = 0, l, r, x, y, c[510];
int g[510][510], fl = 0, a2, a3 = -1000000;
long long int ans[550], cnt = 0;
vector<int> v;
int main() {
  ios_base::sync_with_stdio(false);
  scanf("%d", &n);
  for (i = 1; i <= n; i++) {
    for (j = 1; j <= n; j++) {
      scanf("%d", &a);
      g[i][j] = a;
    }
  }
  for (i = 0; i < n; i++) {
    scanf("%d", &c[i]);
  }
  for (i = n - 1; i >= 0; i--) {
    k = v.size();
    for (x = 0; x < k; x++) {
      d[c[i]][v[x]] = g[c[i]][v[x]];
      for (y = 0; y < k; y++) {
        if (d[c[i]][v[x]] == 0) d[c[i]][v[x]] = INF;
        d[c[i]][v[x]] = min(d[c[i]][v[x]], g[c[i]][v[y]] + d[v[y]][v[x]]);
      }
      cnt += d[c[i]][v[x]] * 1ll;
    }
    for (x = 0; x < k; x++) {
      d[v[x]][c[i]] = g[v[x]][c[i]];
      for (y = 0; y < k; y++) {
        if (d[v[x]][c[i]] == 0) d[v[x]][c[i]] = INF;
        d[v[x]][c[i]] = min(d[v[x]][c[i]], d[v[x]][v[y]] + g[v[y]][c[i]]);
      }
      cnt += d[v[x]][c[i]] * 1ll;
    }
    for (x = 0; x < k; x++) {
      for (y = 0; y < k; y++) {
        if (x == y) continue;
        cnt -= d[v[x]][v[y]] * 1ll;
        if (d[v[x]][v[y]] == 0) d[v[x]][v[y]] = INF;
        d[v[x]][v[y]] = min(d[v[x]][c[i]] + d[c[i]][v[y]], d[v[x]][v[y]]);
        cnt += d[v[x]][v[y]] * 1ll;
      }
    }
    v.push_back(c[i]);
    ans[i] = cnt;
  }
  for (i = 0; i < n; i++) {
    cout << ans[i] << " ";
  }
  return 0;
}
