#include <bits/stdc++.h>
using namespace std;
int n;
vector<int> a, b, g, ar;
vector<vector<int> > edg, nxt;
vector<long long> d;
long long f(int v) {
  long long res = 0;
  for (int w : edg[v]) {
    long long tmp = f(w) + a[w];
    if (tmp > 0) {
      res += tmp;
      nxt[w].push_back(v);
      g[v]++;
    } else {
      nxt[v].push_back(w);
      g[w]++;
    }
  }
  return d[v] = res;
}
int main(void) {
  cin >> n;
  a.assign(n, 0);
  b.assign(n, 0);
  g.assign(n, 0);
  edg.assign(n, vector<int>());
  nxt.assign(n, vector<int>());
  for (int i = 0; i < n; i++) cin >> a[i];
  vector<int> c;
  for (int i = 0; i < n; i++) {
    cin >> b[i];
    if (b[i] == -1) {
      c.push_back(i);
      continue;
    }
    b[i]--;
    edg[b[i]].push_back(i);
  }
  long long ans = 0;
  d.assign(n, 0);
  for (int i = 0; i < n; i++) {
    if (b[i] == -1) f(i);
  }
  for (int i = 0; i < n; i++) {
    ans += d[i] + a[i];
  }
  queue<int> q;
  for (int i = 0; i < n; i++) {
    if (g[i] == 0) q.push(i);
  }
  while (!q.empty()) {
    int v = q.front();
    q.pop();
    ar.push_back(v);
    for (int w : nxt[v]) {
      g[w]--;
      if (g[w] == 0) q.push(w);
    }
  }
  cout << ans << endl;
  for (int v : ar) cout << v + 1 << " ";
  cout << endl;
}
