#include <bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 10;
const int mod = 1e9 + 7;
int read() {
  int x = 0, f = 1;
  char c = getchar();
  while (c < '0' || c > '9') {
    if (c == '-') f = -1;
    c = getchar();
  }
  while (c >= '0' && c <= '9') x = (x << 1) + (x << 3) + c - '0', c = getchar();
  return x * f;
}
int n;
int v[maxn];
vector<int> g[maxn];
int st1[maxn], st2[maxn];
int top1, top2;
int vis[maxn];
long long dp[maxn], answer = 0;
void dfs(int u) {
  dp[u] = v[u];
  for (int v : g[u]) {
    dfs(v);
    dp[u] += max(dp[v], 0ll);
  }
  if (dp[u] <= 0) {
    st2[++top2] = u;
    answer += dp[u];
  } else {
    st1[++top1] = u;
    answer += dp[u];
  }
}
int main() {
  n = read();
  for (int i = 1; i <= n; i++) {
    v[i] = read();
  }
  for (int i = 1; i <= n; i++) {
    int u, v = i;
    u = read();
    if (~u)
      g[u].push_back(v);
    else
      vis[v] = true;
  }
  for (int i = 1; i <= n; i++)
    if (vis[i]) dfs(i);
  cout << answer << endl;
  for (int i = 1; i <= top1; i++) {
    cout << st1[i] << ' ';
  }
  for (int i = top2; i; i--) {
    cout << st2[i] << ' ';
  }
  cout << endl;
}
