#include <bits/stdc++.h>
using namespace std;
long long in() {
  long long a;
  scanf("%lld", &a);
  return a;
}
double din() {
  double a;
  scanf("%lf", &a);
  return a;
}
long long bigmod(long long b, long long p, long long md) {
  if (p == 0) return 1;
  if (p % 2 == 1) {
    return ((b % md) * bigmod(b, p - 1, md)) % md;
  } else {
    long long y = bigmod(b, p / 2, md);
    return (y * y) % md;
  }
}
long long gcd(long long a, long long b) {
  if (b == 0)
    return a;
  else
    return gcd(b, a % b);
}
long long getRandom(long long a, long long b) {
  long long ret = (long long)rand() * (long long)rand();
  ret %= (b - a + 1);
  ret += a;
  return ret;
}
long long ar[200005], vis[200005], ans[200005], val[200005];
vector<int> adj[200005];
stack<int> st;
void dfs(int u) {
  for (int i = 0; i < adj[u].size(); i++) {
    int v = adj[u][i];
    if (vis[v] == 0) {
      vis[v] = 1;
      dfs(v);
    }
  }
  st.push(u);
}
int main() {
  int n = in();
  for (int i = 1; i <= n; i++) ar[i] = in();
  for (int i = 1; i <= n; i++) {
    int x = in();
    val[i] = x;
    if (x != -1) adj[i].push_back(x);
  }
  for (int i = 1; i <= n; i++) {
    if (vis[i] == 0) {
      vis[i] = 1;
      dfs(i);
    }
  }
  memset(vis, 0, sizeof vis);
  vector<int> v;
  long long cnt = 0, pos = 0;
  while (!st.empty()) {
    int x = st.top();
    if (ar[x] < 0)
      v.push_back(x);
    else {
      ans[pos++] = x;
      cnt += ar[x];
      if (val[x] != -1) ar[val[x]] += ar[x];
    }
    st.pop();
  }
  for (int i = v.size() - 1; i >= 0; i--) {
    int x = v[i];
    ans[pos++] = x;
    cnt += ar[x];
    if (val[x] != -1) ar[val[x]] += ar[x];
  }
  printf("%lld\n", (long long)cnt);
  for (int i = 0; i < pos; i++) printf("%lld ", ans[i]);
  puts("");
}
