#include <bits/stdc++.h>
using namespace std;
const int N = 300000, M = 1000000;
struct edge {
  int head[N], end[M], next[M], val[M], tot;
  void reset() {
    tot = 0;
    memset(head, 0, sizeof(head));
  }
  edge() { reset(); }
  void add(int x, int y, int v) {
    next[++tot] = head[x];
    head[x] = tot;
    end[tot] = y;
    val[tot] = v;
    swap(x, y);
    next[++tot] = head[x];
    head[x] = tot;
    end[tot] = y;
    val[tot] = v;
  }
} e;
int a[N], b[N], n;
long long ans, f[N];
void dp(int x) {
  int v;
  f[x] = a[x];
  for (int i = e.head[x]; i; i = e.next[i]) {
    v = e.end[i];
    if (b[x] != v) {
      dp(v);
      if (f[v] >= 0) f[x] += f[v];
    }
  }
}
void print_ans(int x) {
  int v;
  for (int i = e.head[x]; i; i = e.next[i]) {
    v = e.end[i];
    if (b[x] != v && f[v] >= 0) print_ans(v);
  }
  printf("%d ", x);
  for (int i = e.head[x]; i; i = e.next[i]) {
    v = e.end[i];
    if (b[x] != v && f[v] < 0) print_ans(v);
  }
}
int main() {
  scanf("%d", &n);
  for (int i = 1; i <= n; ++i) scanf("%d", &a[i]);
  for (int i = 1; i <= n; ++i) {
    scanf("%d", &b[i]);
    if (b[i] != -1) e.add(i, b[i], 0);
  }
  for (int i = 1; i <= n; ++i) {
    if (b[i] == -1) {
      dp(i);
    }
  }
  ans = 0;
  for (int i = 1; i <= n; ++i) {
    ans += f[i];
  }
  printf("%lld\n", ans);
  for (int i = 1; i <= n; ++i)
    if (b[i] == -1) {
      print_ans(i);
    }
  return 0;
}
