#include <bits/stdc++.h>
using namespace std;
int n;
long long a[200005];
int b[200005];
int in_deg[200005];
long long total = 0;
queue<int> ans;
stack<int> pending;
void solve() {
  queue<int> q;
  for (int i = 1; i <= n; i++) {
    if (in_deg[i] == 0) {
      q.push(i);
    }
  }
  while (!q.empty()) {
    int u = q.front();
    q.pop();
    if (a[u] < 0) {
      pending.push(u);
    } else {
      ans.push(u);
      total += a[u];
      if (b[u] != -1) {
        a[b[u]] += a[u];
      }
    }
    if (b[u] == -1) continue;
    in_deg[b[u]]--;
    if (in_deg[b[u]] == 0) {
      q.push(b[u]);
    }
  }
  while (!pending.empty()) {
    ans.push(pending.top());
    total += a[pending.top()];
    pending.pop();
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  cin >> n;
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
  }
  for (int i = 1; i <= n; i++) {
    cin >> b[i];
    if (b[i] == -1) continue;
    in_deg[b[i]]++;
  }
  solve();
  cout << total << '\n';
  while (!ans.empty()) {
    cout << ans.front() << ' ';
    ans.pop();
  }
  cout << '\n';
  return 0;
}
