#include <bits/stdc++.h>
using namespace std;
template <typename Arg1>
void __f(const char *name, Arg1 &&arg1) {
  cerr << name << " : " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void __f(const char *names, Arg1 &&arg1, Args &&...args) {
  const char *comma = strchr(names + 1, ',');
  cerr.write(names, comma - names) << " : " << arg1 << " | ";
  __f(comma + 1, args...);
}
long long int power(long long int a, long long int b) {
  if (b == 0) return 1;
  if (b % 2 == 0) return (power((a * a) % 998244353, b / 2)) % 998244353;
  return (a * (power((a * a) % 998244353, b / 2)) % 998244353) % 998244353;
}
long long int modInv(long long int n) { return power(n, 1000000007 - 2); }
long long int nCr(long long int n, long long int r,
                  long long int p = 1000000007) {
  if (r == 0) return 1;
  long long int Fact[n + 1];
  Fact[0] = 1;
  for (long long int i = 1; i <= n; i++) {
    Fact[i] = (Fact[i - 1] * i) % p;
  }
  return (((Fact[n] * modInv(Fact[r])) % 1000000007) *
          (modInv(Fact[n - r]) % 1000000007)) %
         1000000007;
}
double PI = 3.14159265359;
void solve() {
  long long int n, i;
  cin >> n;
  long long int A[n], Inorder[n];
  vector<long long int> V[n];
  for (i = 0; i < n; i++) {
    cin >> A[i];
    Inorder[i] = 0;
  }
  for (i = 0; i < n; i++) {
    long long int a;
    cin >> a;
    a--;
    if (a != -2) {
      Inorder[a]++;
      V[i].push_back(a);
    }
  }
  queue<long long int> q;
  for (i = 0; i < n; i++) {
    if (Inorder[i] == 0) {
      q.push(i);
    }
  }
  long long int ans = 0;
  vector<long long int> Ans1, Ans2;
  while (!q.empty()) {
    long long int s = q.front();
    ans += A[s];
    if (A[s] > 0)
      Ans1.push_back(s + 1);
    else
      Ans2.push_back(s + 1);
    q.pop();
    for (long long int ind : V[s]) {
      Inorder[ind]--;
      if (A[s] > 0) {
        A[ind] += A[s];
      }
      if (Inorder[ind] == 0) {
        q.push(ind);
      }
    }
  }
  cout << ans << endl;
  for (i = 0; i < Ans1.size(); i++) cout << Ans1[i] << " ";
  for (i = Ans2.size() - 1; i >= 0 && Ans2.size() > 0; i--)
    cout << Ans2[i] << " ";
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long int t = 1;
  while (t--) {
    solve();
  }
}
