#include <bits/stdc++.h>
using namespace std;
template <typename T>
void read(T &x) {
  x = 0;
  long long f = 1;
  char ch = getchar();
  while (!isdigit(ch)) {
    if (ch == '-') f = -1;
    ch = getchar();
  }
  while (isdigit(ch)) {
    x = x * 10 + (ch ^ 48);
    ch = getchar();
  }
  return x *= f, void();
}
const long long N = 2e5 + 5;
long long n, a[N], b[N], p[N], tot, indu[N], ans;
vector<long long> g[N];
queue<long long> q;
signed main() {
  read(n);
  for (long long i = 1; i <= n; i++) read(a[i]);
  for (long long i = 1; i <= n; i++) read(b[i]), ++indu[b[i]];
  for (long long i = 1; i <= n; i++)
    if (!indu[i]) q.push(i);
  while (!q.empty()) {
    long long u = q.front();
    q.pop();
    ans += a[u];
    if (b[u] == -1) continue;
    if (a[u] > 0) {
      g[u].push_back(b[u]);
      a[b[u]] += a[u];
    } else {
      g[b[u]].push_back(u);
    }
    if (--indu[b[u]] == 0) q.push(b[u]);
  }
  printf("%lld\n", ans);
  for (long long i = 1; i <= n; i++)
    for (long long v : g[i]) ++indu[v];
  for (long long i = 1; i <= n; i++)
    if (!indu[i]) q.push(i);
  while (!q.empty()) {
    long long u = q.front();
    q.pop();
    printf("%lld ", u);
    for (long long v : g[u])
      if (--indu[v] == 0) q.push(v);
  }
  puts("");
  return 0;
}
