#include <bits/stdc++.h>
using namespace std;
const int buf_size = 1e5 + 5;
char buf[buf_size], *S, *T;
inline char gc() {
  if (S == T) T = (S = buf) + fread(buf, 1, buf_size, stdin);
  return S != T ? *(S++) : EOF;
}
inline int in() {
  int x = 0, f = 1;
  char c = gc();
  while (c < '0' || c > '9') {
    if (c == '-') f = -1;
    c = gc();
  }
  while (c >= '0' && c <= '9') x = x * 10 + c - 48, c = gc();
  return x * f;
}
const int N = 2e5 + 5;
int n, cnt;
long long a[N], b[N], d[N], e[N];
long long ans;
queue<int> q;
vector<int> v[N];
int main() {
  n = in();
  for (int i = 1; i <= n; i++) a[i] = in();
  for (int i = 1; i <= n; i++) b[i] = in();
  for (int i = 1; i <= n; i++) {
    if (b[i] != -1) d[b[i]]++;
  }
  for (int i = 1; i <= n; i++)
    if (d[i] == 0) q.push(i);
  while (q.size()) {
    int x = q.front();
    q.pop();
    ans += a[x];
    if (a[x] >= 0) {
      if (b[x] != -1) {
        a[b[x]] += a[x];
        v[x].push_back(b[x]);
        e[b[x]]++;
        d[b[x]]--;
        if (d[b[x]] == 0) q.push(b[x]);
      }
    } else {
      if (b[x] != -1) {
        v[b[x]].push_back(x);
        d[b[x]]--;
        e[x]++;
        if (d[b[x]] == 0) q.push(b[x]);
      }
    }
  }
  for (int i = 1; i <= n; i++)
    if (e[i] == 0) q.push(i);
  cout << ans << endl;
  while (q.size()) {
    int x = q.front();
    q.pop();
    printf("%d ", x);
    for (int i = 0; i < v[x].size(); i++) {
      int y = v[x][i];
      e[y]--;
      if (e[y] == 0) q.push(y);
    }
  }
  return 0;
}
