#include <bits/stdc++.h>
#pragma GCC optimize(2)
#pragma GCC optimize(3)
const long long INF = 0x3f3f3f3f;
const long long NINF = -INF - 1;
const double PI = acos(-1);
const long long mod = 1e9 + 7;
const long long maxn = 2e5 + 10;
const double eps = 1e-8;
using namespace std;
long long a[maxn], b[maxn];
bool v[maxn];
long long ans;
vector<long long> mp2[maxn], mp1[maxn], V;
void ssdabc(long long A, long long B) {
  if (B == 1) {
    if (a[A] >= 0) {
      ans += a[A];
      V.push_back(A);
      v[A] = 1;
      for (long long i = (0); i < (mp1[A].size()); i++) {
        a[mp1[A][i]] += a[A];
        ssdabc(mp1[A][i], 2);
      }
    } else {
      v[A] = 1;
      for (long long i = (0); i < (mp1[A].size()); i++) {
        ssdabc(mp1[A][i], 2);
      }
      ans += a[A];
      V.push_back(A);
    }
  } else {
    bool yep = 1;
    for (long long i = (0); i < (mp2[A].size()); i++) {
      if (v[mp2[A][i]] == 0) {
        yep = 0;
        ssdabc(mp2[A][i], 2);
      }
    }
    if (yep == 1) ssdabc(A, 1);
  }
}
signed main() {
  ios_base::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  long long n;
  cin >> n;
  for (long long i = (1); i <= (n); i++) {
    cin >> a[i];
  }
  for (long long i = (1); i <= (n); i++) {
    cin >> b[i];
    if (b[i] != -1) {
      mp1[i].push_back(b[i]);
      mp2[b[i]].push_back(i);
    } else {
      continue;
    }
  }
  for (long long i = (1); i <= (n); i++) {
    long long k = mp2[i].size();
    if (!v[i] && !k) {
      ssdabc(i, 2);
    }
  }
  cout << ans << '\n';
  for (long long i = (0); i < (V.size()); i++) {
    cout << V[i] << " ";
  }
  return 0;
}
