#include <bits/stdc++.h>
const int N = 501;
const int inf = 0x3f3f3f3f;
using namespace std;
int d[N][N], a[N], w[N][N];
long long ans[N];
bool used1[N], used2[N];
int main() {
  memset(w, 0x3f3f3f3f, sizeof(w));
  int n, i, j, k, p;
  scanf("%d", &n);
  for (i = 0; i < n; i++)
    for (j = 0; j < n; j++) scanf("%d", &d[i][j]);
  for (i = 0; i < n; i++) {
    scanf("%d", &a[n - i - 1]);
    --a[n - i - 1];
  }
  w[a[0]][a[0]] = 0;
  ans[0] = 0;
  for (i = 1; i < n; i++) {
    int x = a[i];
    w[x][x] = 0;
    memset(used1, false, sizeof(used1));
    memset(used2, false, sizeof(used2));
    for (j = 0; j < i; j++) {
      w[x][a[j]] = d[x][a[j]];
      w[a[j]][x] = d[a[j]][x];
    }
    for (j = 0; j < i - 1; j++) {
      int mind1 = inf, mink1;
      int mind2 = inf, mink2;
      for (k = 0; k < i; k++) {
        if (!used1[a[k]] && w[x][a[k]] < mind1) {
          mind1 = w[x][a[k]];
          mink1 = a[k];
        }
        if (!used2[a[k]] && w[a[k]][x] < mind2) {
          mind2 = w[a[k]][x];
          mink2 = a[k];
        }
      }
      used1[mink1] = true;
      used2[mink2] = true;
      for (k = 0; k < i; k++) {
        if (w[x][mink1] + w[mink1][a[k]] < w[x][a[k]])
          w[x][a[k]] = w[x][mink1] + w[mink1][a[k]];
        if (w[mink2][x] + w[a[k]][mink2] < w[a[k]][x])
          w[a[k]][x] = w[mink2][x] + w[a[k]][mink2];
      }
    }
    for (j = 0; j < i; j++)
      for (k = 0; k < i; k++)
        if (w[a[j]][a[k]] > w[a[j]][x] + w[x][a[k]])
          w[a[j]][a[k]] = w[a[j]][x] + w[x][a[k]];
    for (j = 0; j <= i; j++)
      for (k = 0; k <= i; k++) ans[i] += (long long)w[a[j]][a[k]];
  }
  for (i = n - 1; i >= 0; i--) printf("%I64d ", ans[i]);
  return 0;
}
