#include <bits/stdc++.h>
using namespace std;
ifstream fin("input");
void init() {
  cin.tie(NULL);
  ios_base::sync_with_stdio(false);
}
const int mx = 3e5;
int n, father[mx];
vector<int> a, b;
vector<int> g[mx], before[mx], after[mx];
vector<int> q;
long long total = 0;
bool visited[mx];
void read() {
  cin >> n;
  a.resize(n + 1);
  b.resize(n + 1);
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
  }
  for (int i = 1; i <= n; i++) {
    cin >> b[i];
  }
}
void topsort(int node) {
  for (int k : before[node]) {
    topsort(k);
  }
  q.push_back(node);
  for (int k : after[node]) {
    topsort(k);
  }
}
long long dfs(int node) {
  visited[node] = true;
  long long to_add = 0, next;
  for (int k : g[node]) {
    next = dfs(k);
    if (next >= 0) {
      before[node].push_back(k);
      to_add += next;
    } else {
      after[node].push_back(k);
    }
  }
  total += a[node] + to_add;
  return a[node] + to_add;
}
int root(int node) {
  while (father[node]) {
    node = father[node];
  }
  return node;
}
void solve() {
  for (int i = 1; i <= n; i++) {
    if (b[i] != -1) {
      g[b[i]].push_back(i);
      father[i] = b[i];
    }
  }
  for (int i = 1; i <= n; i++) {
    if (!visited[i]) {
      int node = root(i);
      dfs(node);
      topsort(node);
    }
  }
  cout << total << endl;
  for (int k : q) cout << k << " ";
}
int main() {
  init();
  read();
  solve();
  return 0;
}
