#include <bits/stdc++.h>
using namespace std;
const long double EPS = 1e-8;
const long long INF = 1e9 + 7;
const long long MOD = 1e9 + 7;
const long long MAXN = 2e5;
vector<long long> gr[MAXN], order, used;
void dfs(long long u) {
  used[u] = 1;
  for (long long v : gr[u]) {
    if (!used[v]) {
      dfs(v);
    }
  }
  order.push_back(u);
}
void solve() {
  long long n;
  cin >> n;
  vector<long long> a(n), b(n);
  for (long long& i : a) {
    cin >> i;
  }
  for (long long& i : b) {
    cin >> i;
    if (i > 0) {
      --i;
    }
  }
  for (long long i = 0; i < n; ++i) {
    if (b[i] >= 0) {
      gr[i].push_back(b[i]);
    }
  }
  used.assign(n, 0);
  for (long long i = 0; i < n; ++i) {
    if (!used[i]) {
      dfs(i);
    }
  }
  reverse(order.begin(), order.end());
  long long ans = 0;
  vector<long long> pos;
  vector<long long> later;
  for (long long u : order) {
    if (a[u] > 0) {
      long long v = b[u];
      if (v >= 0) {
        a[v] += a[u];
      }
      pos.push_back(u + 1);
      ans += a[u];
    } else {
      later.push_back(u);
    }
  }
  reverse(later.begin(), later.end());
  for (long long u : later) {
    long long v = b[u];
    if (v >= 0) {
      a[v] += a[u];
    }
    pos.push_back(u + 1);
    ans += a[u];
  }
  cout << ans << "\n";
  copy(pos.begin(), pos.end(), ostream_iterator<long long>(cout, " "));
  cout << "\n";
  ;
}
signed main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t;
  t = 1;
  for (long long i = 0; i < t; ++i) {
    solve();
  }
  return 0;
}
