#include <bits/stdc++.h>
using namespace std;
const long long MAX = 2e5;
void solve() {
  long long n;
  cin >> n;
  vector<long long> a(n + 10), b(n + 10), entrada(n + 10), resp, fim;
  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) {
      entrada[b[i]]++;
    }
  }
  queue<long long> q;
  for (long long i = 1; i <= n; i++) {
    if (entrada[i] == 0) q.push(i);
  }
  long long ans = 0;
  while (q.size()) {
    long long id = q.front();
    q.pop();
    ans += a[id];
    if (a[id] >= 0) {
      resp.push_back(id);
    } else {
      fim.push_back(id);
    }
    if (b[id] != -1) {
      entrada[b[id]]--;
      if (a[id] > 0) a[b[id]] += a[id];
      if (entrada[b[id]] == 0) {
        q.push(b[id]);
      }
    }
  }
  while (fim.size()) resp.push_back(fim.back()), fim.pop_back();
  cout << ans << '\n';
  for (auto it : resp) cout << it << ' ';
}
int32_t main() {
  long long t = 1;
  while (t--) solve();
  return 0;
}
