#include <bits/stdc++.h>
using namespace std;
int n;
long long a[202020], b[202020], chk[202020];
vector<int> g[202020];
int deg[202020];
vector<int> order;
void top_sort() {
  queue<int> q;
  for (int i = 1; i <= n; i++) {
    if (!deg[i]) q.push(i);
  }
  while (q.size()) {
    int now = q.front();
    q.pop();
    order.push_back(now);
    for (auto i : g[now]) {
      if (!--deg[i]) q.push(i);
    }
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(nullptr);
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  for (int i = 1; i <= n; i++) cin >> b[i];
  for (int i = 1; i <= n; i++) {
    if (b[i] != -1) g[i].push_back(b[i]), deg[b[i]]++;
  }
  top_sort();
  long long sum = 0;
  vector<int> ans;
  for (auto i : order) {
    if (a[i] >= 0) {
      sum += a[i];
      ans.push_back(i);
      chk[i] = 1;
      if (b[i] != -1) a[b[i]] += a[i];
    }
  }
  reverse(order.begin(), order.end());
  for (auto i : order) {
    if (chk[i]) continue;
    sum += a[i];
    ans.push_back(i);
    chk[i] = 1;
    if (b[i] != -1) a[b[i]] += a[i];
  }
  cout << sum << "\n";
  for (auto i : ans) cout << i << " ";
}
