#include <bits/stdc++.h>
using namespace std;
vector<long long> adj[200001];
long long a[200001];
vector<long long> start;
stack<long long> last;
long long ans;
bool f;
void dfs(long long);
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  long long n;
  cin >> n;
  set<long long> roots;
  for (long long i = 1; i <= n; i++) roots.insert(i);
  for (long long i = 1; i <= n; i++) cin >> a[i];
  long long x;
  for (long long i = 1; i <= n; i++) {
    cin >> x;
    if (x != -1) {
      adj[x].push_back(i);
      roots.erase(i);
    }
  }
  start.clear();
  while (!last.empty()) last.pop();
  ans = 0;
  for (auto x : roots) {
    dfs(x);
  }
  cout << ans << '\n';
  for (auto x : start) {
    cout << x << ' ';
  }
  while (!last.empty()) {
    cout << last.top() << ' ';
    last.pop();
  }
}
void dfs(long long v) {
  for (auto x : adj[v]) {
    dfs(x);
    if (a[x] > 0) a[v] += a[x];
  }
  ans += a[v];
  if (a[v] > 0) {
    start.push_back(v);
  } else {
    last.push(v);
  }
}
