#include <bits/stdc++.h>
long long dx[4] = {-1, 0, 1, 0};
long long dy[4] = {0, -1, 0, 1};
using namespace std;
vector<vector<long long> > g;
vector<long long> a, b, roots, vis, topo;
void dfs(long long root) {
  vis[root] = 1;
  for (long long i = 0; i < g[root].size(); i++) {
    if (!vis[g[root][i]]) dfs(g[root][i]);
  }
  topo.push_back(root);
}
void solve() {
  vector<long long> l1, l2;
  for (long long i = 0; i < roots.size(); i++) {
    dfs(roots[i]);
  }
  long long sum = 0;
  for (long long i = 0; i < topo.size(); i++) {
    long long x = topo[i];
    sum += a[x];
    if (a[x] > 0 && b[x] != -1) a[b[x] - 1] += a[x];
    if (a[x] > 0)
      l1.push_back(x);
    else
      l2.push_back(x);
  }
  cout << sum << endl;
  for (long long i = 0; i < l1.size(); i++) cout << l1[i] + 1 << ' ';
  if (l2.size() > 0) {
    for (long long i = l2.size() - 1; i >= 0; i--) cout << l2[i] + 1 << ' ';
  }
}
int32_t main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  long long t = 1;
  while (t--) {
    long long n;
    cin >> n;
    a.resize(n);
    b.resize(n);
    vis.resize(n + 1, 0);
    for (long long i = 0; i < n; i++) cin >> a[i];
    for (long long i = 0; i < n; i++) {
      cin >> b[i];
    }
    g.resize(n + 1);
    for (long long i = 0; i < n; i++) {
      if (b[i] != -1) {
        g[b[i] - 1].push_back(i);
      } else
        roots.push_back(i);
    }
    solve();
    cout << endl;
  }
}
