#include <bits/stdc++.h>
using namespace std;
const int INF = 100000000;
int N;
int G[510][510];
int rev[510];
int cur[510][510];
int len[510][510];
long long sum[510];
int main() {
  istream& in = cin;
  in >> N;
  for (int i = 1; i <= N; i++) {
    for (int j = 1; j <= N; j++) {
      in >> G[i][j];
    }
  }
  for (int i = 0; i < N; i++) {
    in >> rev[i];
  }
  for (int i = 1; i <= N; i++) {
    for (int j = 1; j <= N; j++) {
      cur[i][j] = -1;
      len[i][j] = INF;
    }
  }
  for (int add = N - 1; add >= 0; add--) {
    int av = rev[add];
    cur[av][av] = 0;
    for (int i = 1; i <= N; i++) {
      if (cur[i][i] == -1) continue;
      cur[av][i] = G[av][i];
      cur[i][av] = G[i][av];
    }
    priority_queue<pair<int, int>, vector<pair<int, int> >,
                   greater<pair<int, int> > >
        que;
    que.push(make_pair(0, av));
    len[av][av] = 0;
    while (!que.empty()) {
      pair<int, int> p = que.top();
      que.pop();
      int cost = p.first;
      int v = p.second;
      if (len[av][v] < cost) continue;
      for (int to = 1; to <= N; to++) {
        if (cur[v][to] == -1) continue;
        if (cur[v][to] + cost < len[av][to]) {
          len[av][to] = cur[v][to] + cost;
          que.push(make_pair(len[av][to], to));
        }
      }
    }
    for (int i = 1; i <= N; i++) {
      if (i == av || cur[i][i] == -1) continue;
      len[i][av] = cur[i][av];
      que.push(make_pair(len[i][av], i));
    }
    while (!que.empty()) {
      pair<int, int> p = que.top();
      que.pop();
      int cost = p.first;
      int v = p.second;
      if (len[v][av] < cost) continue;
      for (int from = 1; from <= N; from++) {
        if (cur[from][from] == -1) continue;
        if (len[from][v] + len[v][av] < len[from][av]) {
          len[from][av] = len[from][v] + len[v][av];
          que.push(make_pair(len[from][av], from));
        }
      }
    }
    for (int v = 1; v <= N; v++) {
      for (int to = 1; to <= N; to++) {
        if (cur[v][v] == -1 || cur[to][to] == -1) continue;
        if (len[v][av] + len[av][to] < len[v][to]) {
          len[v][to] = len[v][av] + len[av][to];
        }
      }
    }
    sum[add] = 0;
    for (int i = 1; i <= N; i++) {
      for (int j = 1; j <= N; j++) {
        if (cur[i][i] == -1 || cur[j][j] == -1) continue;
        sum[add] += len[i][j];
      }
    }
  }
  for (int i = 0; i < N; i++) {
    printf("%I64d ", sum[i]);
  }
  return 0;
}
