#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int N = 2e5 + 1;
vector<long long int> a[N];
vector<long long int> order, pos(N);
bool topsort(long long int n) {
  order.clear();
  queue<long long int> q;
  vector<long long int> indeg(n + 1, 0);
  for (long long int i = 1; i <= n; i++)
    for (auto &it : a[i]) indeg[it]++;
  for (long long int i = 1; i <= n; i++)
    if (!indeg[i]) q.push(i);
  long long int idx = 0;
  while (!q.empty()) {
    int v = q.front();
    q.pop();
    order.push_back(v);
    idx++;
    pos[v] = idx;
    for (auto &u : a[v]) {
      indeg[u]--;
      if (!indeg[u]) q.push(u);
    }
  }
  return (order.size() == n);
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long int n;
  cin >> n;
  vector<long long int> a1(n + 1), b(n + 1), c;
  for (long long int i = 1; i <= n; i++) cin >> a1[i];
  for (long long int i = 1; i <= n; i++) {
    cin >> b[i];
    if (b[i] != -1) a[i].push_back(b[i]);
  }
  topsort(n);
  vector<long long int> ans, tmp;
  long long int sum1 = 0, k = 0;
  for (long long int i = 0; i < order.size(); i++) {
    long long int pos = order[i];
    sum1 += a1[pos];
    if (a1[pos] < 0)
      tmp.push_back(pos);
    else {
      if (b[pos] != -1) a1[b[pos]] += a1[pos];
      ans.push_back(pos);
    }
  }
  reverse(tmp.begin(), tmp.end());
  for (long long int i = 0; i < tmp.size(); i++) ans.push_back(tmp[i]);
  cout << sum1 << "\n";
  for (long long int i = 0; i < n; i++) cout << ans[i] << " ";
  return 0;
}
