#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2e5 + 10;
int n;
int inDegree[MAXN];
long long A[MAXN], _A[MAXN], B[MAXN];
vector<int> adj[MAXN];
void build() {
  for (int i = 0; i < n; i++) {
    if (B[i] == -1) continue;
    adj[i].push_back(B[i]);
    inDegree[B[i]]++;
  }
}
vector<int> solve() {
  vector<int> pos, neg;
  queue<int> q;
  for (int i = 0; i < n; i++) {
    if (inDegree[i] == 0) {
      q.push(i);
    }
  }
  while (!q.empty()) {
    int i = q.front();
    q.pop();
    if (A[i] > 0) {
      pos.push_back(i);
      if (B[i] != -1) A[B[i]] += A[i];
    } else {
      neg.push_back(i);
    }
    for (auto v : adj[i]) {
      inDegree[v]--;
      if (inDegree[v] == 0) q.push(v);
    }
  }
  reverse(neg.begin(), neg.end());
  pos.insert(pos.end(), neg.begin(), neg.end());
  return pos;
}
int main() {
  ;
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  ;
  cin >> n;
  for (int i = 0; i < n; i++) {
    cin >> A[i];
    _A[i] = A[i];
  }
  for (int i = 0; i < n; i++) {
    cin >> B[i];
    if (B[i] != -1) B[i]--;
  }
  build();
  long long ans = 0;
  vector<int> v = solve();
  for (auto i : v) {
    ans += _A[i];
    if (B[i] != -1) _A[B[i]] += _A[i];
  }
  cout << ans << '\n';
  for (auto i : v) cout << i + 1 << ' ';
  cout << '\n';
  return 0;
}
