#include <bits/stdc++.h>
using namespace std;
template <class T1, class T2>
ostream& operator<<(ostream& os, const pair<T1, T2>& a) {
  return os << "(" << a.first << "," << a.second << ")";
}
template <class T>
void pv(T a, T b) {
  for (T i = a; i != b; ++i) cout << (*i) << " ";
  cout << endl;
}
template <class T>
void chmin(T& a, const T& b) {
  if (a > b) a = b;
}
template <class T>
void chmax(T& a, const T& b) {
  if (a < b) a = b;
}
long long nextLong() {
  long long x;
  scanf("%lld", &x);
  return x;
}
int main2() {
  int N = nextLong();
  vector<long long> a(N);
  vector<long long> b(N);
  vector<long long> deg(N);
  for (int i = 0, _n = (int)(N); i < _n; ++i) a[i] = nextLong();
  for (int i = 0, _n = (int)(N); i < _n; ++i) {
    b[i] = nextLong() - 1;
    if (b[i] >= 0) deg[b[i]]++;
  }
  queue<int> q;
  for (int i = 0, _n = (int)(N); i < _n; ++i)
    if (deg[i] == 0) {
      q.push(i);
    }
  long long ans = 0;
  vector<int> pos, neg;
  while (!q.empty()) {
    int i = q.front();
    q.pop();
    ans += a[i];
    if (a[i] >= 0)
      pos.push_back(i + 1);
    else
      neg.push_back(i + 1);
    if (b[i] >= 0) {
      if (a[i] > 0) a[b[i]] += a[i];
      deg[b[i]]--;
      if (deg[b[i]] == 0) q.push(b[i]);
    }
  }
  cout << ans << '\n';
  vector<int> as;
  for (int i = 0, _n = (int)(pos.size()); i < _n; ++i) as.push_back(pos[i]);
  reverse((neg).begin(), (neg).end());
  for (int i = 0, _n = (int)(neg.size()); i < _n; ++i) as.push_back(neg[i]);
  for (int i = 0, _n = (int)(N); i < _n; ++i) {
    if (i) cout << ' ';
    cout << as[i];
  }
  cout << '\n';
  return 0;
}
int main() {
  main2();
  return 0;
}
