#include <bits/stdc++.h>
using namespace std;
template <class T>
void chmin(T& a, T b) {
  a = min(a, b);
}
template <class T>
void chmax(T& a, T b) {
  a = max(a, b);
}
constexpr int INF = 1 << 30;
constexpr long long INFL = 1LL << 60;
constexpr long long MOD = 1000000007;
constexpr long double EPS = 1e-12;
long double PI = acos(-1.0);
void solve() {
  long long n;
  cin >> n;
  vector<long long> a(n + 1), b(n + 1);
  for (long long i = 0; i < (n); i++) cin >> a[i + 1];
  for (long long i = 0; i < (n); i++) cin >> b[i + 1];
  vector<long long> deg(n + 1);
  for (long long i = 1; i <= n; i++) {
    if (b[i] != -1) ++deg[b[i]];
  }
  set<tuple<long long, long long> > set;
  vector<long long> ans, ansr;
  long long sum = 0;
  for (long long i = 1; i <= n; i++) {
    set.emplace(deg[i], i);
  }
  while (!set.empty()) {
    tuple<long long, long long> t = *set.begin();
    set.erase(t);
    long long de, idx;
    tie(de, idx) = t;
    sum += a[idx];
    if (b[idx] == -1) {
      ans.push_back(idx);
    } else {
      long long& idx2 = b[idx];
      set.erase(make_tuple(deg[idx2], idx2));
      --deg[idx2];
      set.emplace(deg[idx2], idx2);
      if (a[idx] > 0) {
        a[idx2] += a[idx];
        ans.push_back(idx);
      } else {
        ansr.push_back(idx);
      }
    }
  }
  reverse(ansr.begin(), ansr.end());
  for (long long& i : ansr) ans.push_back(i);
  cout << sum << endl;
  for (long long i = 0; i < ans.size(); i++) {
    if (i > 0) cout << ' ';
    cout << ans[i];
  }
  cout << endl;
  return;
}
int main() {
  std::cin.tie(nullptr);
  std::ios_base::sync_with_stdio(false);
  cout << fixed << setprecision(15);
  solve();
}
