#include <bits/stdc++.h>
using namespace std;
using gg = long long;
constexpr gg MAX = 2e5 + 5;
gg ti, ni;
vector<gg> ai(MAX), bi(MAX), degree(MAX);
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  ti = 1;
  while (ti--) {
    cin >> ni;
    fill(degree.begin(), degree.begin() + ni + 1, 0);
    for (gg i = 1; i <= ni; ++i) {
      cin >> ai[i];
    }
    for (gg i = 1; i <= ni; ++i) {
      cin >> bi[i];
      if (bi[i] != -1) degree[bi[i]]++;
    }
    gg ans = 0;
    vector<gg> pos, neg;
    queue<gg> q;
    for (gg i = 1; i <= ni; ++i)
      if (degree[i] == 0) q.push(i);
    while (!q.empty()) {
      gg p = q.front();
      q.pop();
      if (ai[p] > 0) {
        pos.push_back(p);
      } else {
        neg.push_back(p);
      }
      ans += ai[p];
      if (bi[p] != -1) {
        if (ai[p] > 0) {
          ai[bi[p]] += ai[p];
        }
        if (--degree[bi[p]] == 0) q.push(bi[p]);
      }
    }
    pos.insert(pos.end(), neg.rbegin(), neg.rend());
    cout << ans << "\n";
    for (gg i : pos) {
      cout << i << " ";
    }
    cout << "\n";
  }
  return 0;
}
