#include <bits/stdc++.h>
using namespace std;
const int MAX_N = 501;
int n;
long long adj[MAX_N][MAX_N], ans[MAX_N];
int x[MAX_N];
void solve() {
  for (int k = 1; k <= n; ++k) {
    long long sum = 0;
    if (k > 1) {
      for (int i = 1; i <= k; ++i) {
        for (int j = 1; j <= k; ++j) {
          int a = x[n - i + 1], b = x[n - j + 1], c = x[n - k + 1];
          adj[c][a] = min(adj[c][a], adj[c][b] + adj[b][a]);
          adj[a][c] = min(adj[a][c], adj[a][b] + adj[b][c]);
        }
      }
    }
    for (int i = 1; i <= k; ++i) {
      for (int j = 1; j <= k; ++j) {
        int a = x[n - i + 1], b = x[n - j + 1], c = x[n - k + 1];
        sum += (adj[a][b] = min(adj[a][b], adj[a][c] + adj[c][b]));
      }
    }
    ans[k] = sum;
  }
  for (int i = n; i > 0; --i) {
    if (i == n)
      printf("%I64d", ans[i]);
    else
      printf(" %I64d", ans[i]);
  }
  puts("");
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) {
    for (int j = 1; j <= n; ++j) {
      scanf("%I64d", &adj[i][j]);
    }
  }
  for (int i = 1; i <= n; ++i) scanf("%d", x + i);
  solve();
  return 0;
}
