#include <bits/stdc++.h>
using namespace std;
template <typename T>
void __read(T &a) {
  cin >> a;
}
template <typename T, typename... Args>
void __read(T &a, Args &...args) {
  cin >> a;
  __read(args...);
}
constexpr long long M7 = 1000000007ll;
constexpr long long M9 = 1000000009ll;
constexpr long long MFFT = 998244353ll;
template <class T>
void outv(const T &a) {
  for (auto &x : a) cout << x << ' ';
}
static mt19937 rnd(static_cast<unsigned>(
    chrono::steady_clock::now().time_since_epoch().count()));
auto __fast_io__ = (ios_base::sync_with_stdio(false), cin.tie(nullptr));
int32_t main() {
  long long n;
  __read(n);
  vector<long long> a(n);
  for (signed i = 0; i < (n); i++) cin >> a[i];
  vector<long long> b(n);
  for (signed i = 0; i < (n); i++) cin >> b[i];
  vector<vector<long long>> g(n);
  for (long long i = 0; i < n; ++i) {
    if (b[i] != -1) {
      b[i]--;
      g[b[i]].push_back(i);
    }
  }
  vector<long long> was(n);
  vector<list<long long>> lst(n);
  function<void(long long)> dfs = [&](long long v) {
    was[v] = 1;
    vector<long long> q;
    lst[v] = {v};
    for (long long u : g[v]) {
      if (!was[u]) {
        dfs(u);
      }
      if (a[u] > 0) {
        lst[v].splice(lst[v].begin(), move(lst[u]));
        a[v] += a[u];
      } else {
        lst[v].splice(lst[v].end(), move(lst[u]));
      }
    }
  };
  vector<long long> order;
  long long ans = 0;
  for (long long v = 0; v < n; ++v) {
    if (!was[v]) {
      dfs(v);
    }
    if (b[v] == -1) {
      for (auto &i : lst[v]) {
        order.push_back(i);
      }
    }
    ans += a[v];
  }
  cout << ans << '\n';
  for (auto &v : order) {
    cout << v + 1 << ' ';
  }
  cout << '\n';
  return 0;
}
