#include <bits/stdc++.h>
using namespace std;
const int N = 500 + 5;
int n, node[N], mat[N][N];
long long dist[N][N], result[N];
int main() {
  memset(dist, 0x3f, sizeof dist);
  scanf("%d", &n);
  for (int i = 0; i < n; ++i)
    for (int j = 0; j < n; ++j) scanf("%d", mat[i] + j);
  for (int i = 0; i < n; ++i) {
    scanf("%d", node + i);
    --node[i];
  }
  for (int index = n - 1; index >= 0; --index) {
    for (int i = 0; i < n; ++i) dist[node[index]][i] = mat[node[index]][i];
    for (int i = 0; i < n; i++)
      for (int j = 0; j < n; j++)
        if (dist[node[index]][i] + dist[i][j] < dist[node[index]][j])
          dist[node[index]][j] = dist[node[index]][i] + dist[i][j];
    for (int i = 0; i < n; i++)
      for (int j = 0; j < n; j++)
        if (dist[i][j] + dist[j][node[index]] < dist[i][node[index]])
          dist[i][node[index]] = dist[i][j] + dist[j][node[index]];
    for (int i = 0; i < n; i++)
      for (int j = 0; j < n; j++)
        if (dist[i][node[index]] + dist[node[index]][j] < dist[i][j])
          dist[i][j] = dist[i][node[index]] + dist[node[index]][j];
    long long sum = 0;
    for (int i = n - 1; i >= index; --i)
      for (int j = n - 1; j >= index; --j) sum += dist[node[i]][node[j]];
    result[index] = sum;
  }
  for (int i = 0; i < n; ++i) printf("%lld ", result[i]);
  return 0;
}
