#include <bits/stdc++.h>
#pragma GCC optimize(3, "Ofast", "inline")
using namespace std;
mt19937 rnd(chrono::high_resolution_clock::now().time_since_epoch().count());
const long long maxn = (long long)3e5 + 5;
const long long mod = 998244353;
const long long inf = 0x3f3f3f3f;
long long T = 1;
long long a[maxn], b[maxn];
vector<long long> v[maxn];
long long in[maxn];
void solve() {
  long long n;
  cin >> n;
  for (long long i = 1; i <= n; ++i) cin >> a[i];
  for (long long i = 1; i <= n; ++i) {
    cin >> b[i];
    if (b[i] != -1) {
      v[i].push_back(b[i]);
      ++in[b[i]];
    }
  }
  long long ans = 0;
  queue<long long> q;
  for (long long i = 1; i <= n; ++i) {
    if (in[i] == 0) {
      q.push(i);
    }
  }
  vector<long long> tmp;
  stack<long long> last;
  while (!q.empty()) {
    long long now = q.front();
    if (a[now] > 0)
      tmp.push_back(now);
    else
      last.push(now);
    ans += a[now];
    q.pop();
    for (auto &to : v[now]) {
      if (a[now] > 0) a[to] += a[now];
      --in[to];
      if (in[to] == 0) {
        q.push(to);
      }
    }
  }
  cout << ans << '\n';
  for (auto &to : tmp) cout << to << ' ';
  while (!last.empty()) {
    cout << last.top() << ' ';
    last.pop();
  }
}
signed main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  cout.tie(0);
  ;
  while (T--) solve();
  return 0;
}
