#include <bits/stdc++.h>
using namespace std;
const long long maxn = 501;
long long dist[500][500], sum = 0;
int32_t main() {
  long long n;
  cin >> n;
  for (long long i = 0; i < n; i++) {
    for (long long j = 0; j < n; j++) {
      cin >> dist[i][j];
    }
  }
  vector<long long> add, ans, cur;
  for (long long i = 0; i < n; i++) {
    long long a;
    cin >> a;
    a--;
    add.push_back(a);
  }
  reverse(add.begin(), add.end());
  for (auto y : add) {
    for (auto k : cur) {
      sum += dist[y][k] + dist[k][y];
    }
    for (auto k : cur) {
      for (auto j : cur) {
        sum -= dist[y][j];
        dist[y][j] = min(dist[y][j], dist[y][k] + dist[k][j]);
        sum += dist[y][j];
      }
    }
    for (auto k : cur) {
      for (auto i : cur) {
        sum -= dist[i][y];
        dist[i][y] = min(dist[i][y], dist[i][k] + dist[k][y]);
        sum += dist[i][y];
      }
    }
    for (auto i : cur) {
      for (auto j : cur) {
        sum -= dist[i][j];
        dist[i][j] = min(dist[i][j], dist[i][y] + dist[y][j]);
        sum += dist[i][j];
      }
    }
    ans.push_back(sum);
    cur.push_back(y);
  }
  reverse(ans.begin(), ans.end());
  for (auto b : ans) cout << b << ' ';
}
