#include <bits/stdc++.h>
using namespace std;
long long mp[505][505], dist[505][505];
long long ans = 0;
vector<long long> remain, ret;
void update(long long w) {
  for (register long long i = 0; i < remain.size(); ++i) {
    for (register long long j = 0; j < remain.size(); ++j) {
      long long u = remain[i], v = remain[j];
      dist[u][w] = min(dist[u][w], dist[u][v] + dist[v][w]);
      dist[w][u] = min(dist[w][u], dist[w][v] + dist[v][u]);
    }
  }
  for (register long long i = 0; i < remain.size(); ++i) {
    for (register long long j = 0; j < remain.size(); ++j) {
      long long u = remain[i], v = remain[j];
      long long temp = dist[u][v];
      dist[u][v] = min(dist[u][v], dist[u][w] + dist[w][v]);
      ans += dist[u][v] - temp;
    }
  }
  for (long long i = 0; i < remain.size(); ++i) {
    ans += dist[w][remain[i]];
    ans += dist[remain[i]][w];
  }
  remain.push_back(w);
  ret.push_back(ans);
}
int main() {
  long long n;
  scanf("%I64d", &n);
  for (long long i = 1; i <= n; ++i) {
    for (long long j = 1; j <= n; ++j) {
      scanf("%I64d", &mp[i][j]);
    }
  }
  vector<long long> del;
  for (long long i = 1; i <= n; ++i) {
    long long t;
    scanf("%I64d", &t);
    del.push_back(t);
  }
  reverse(del.begin(), del.end());
  memcpy(dist, mp, sizeof(mp));
  for (long long i = 0; i < n; ++i) {
    update(del[i]);
  }
  for (long long i = n - 1; i >= 0; --i) {
    printf("%I64d\n", ret[i]);
  }
  return 0;
}
