#include <bits/stdc++.h>
using namespace std;
int dcmp(double x, double y) {
  return fabs(x - y) <= 1e-9 ? 0 : x < y ? -1 : 1;
}
const int MAX = 510;
long long dist[MAX][MAX];
int n, kk;
vector<long long> ans;
void floyd_all(vector<long long> vertex) {
  long long sum = 0;
  for (int k = 0; k < ((int)((vertex).size())); ++k) {
    for (int i = 0; i < (int)(n); ++i) {
      for (int j = 0; j < (int)(n); ++j) {
        dist[i][j] = min(dist[i][j], dist[i][vertex[k]] + dist[vertex[k]][j]);
      }
    }
    for (int i = 0; i <= k; i++) {
      for (int j = 0; j <= k; j++) {
        sum += dist[vertex[i]][vertex[j]];
      }
    }
    ans.push_back(sum);
    sum = 0;
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  ;
  cin >> n;
  for (int i = 0; i < (int)(n); ++i) {
    for (int j = 0; j < (int)(n); ++j) {
      cin >> dist[i][j];
    }
  }
  vector<long long> vertex;
  for (int i = 0; i < (int)(n); ++i) {
    int tmp;
    cin >> tmp;
    tmp--;
    vertex.push_back(tmp);
  }
  reverse(((vertex).begin()), ((vertex).end()));
  floyd_all(vertex);
  reverse(((ans).begin()), ((ans).end()));
  for (int i = 0; i < ((int)((ans).size())); ++i) {
    cout << ans[i] << ' ';
  }
}
