#include <bits/stdc++.h>
using namespace std;
vector<long long> a;
vector<vector<long long>> graph;
vector<long long> order;
vector<long long> dumbest;
long long ans = 0;
void dfs(long long v, long long pred = -1) {
  for (long long u : graph[v]) {
    if (u != pred) {
      dfs(u, v);
    }
  }
  if (pred == -1) {
    order.emplace_back(v);
    ans += a[v];
    return;
  }
  if (a[v] >= 0) {
    order.emplace_back(v);
    ans += a[v];
    a[pred] += a[v];
    return;
  } else {
    dumbest.emplace_back(v);
    ans += a[v];
    return;
  }
}
int32_t main() {
  cin.tie(0);
  cout.tie(0);
  iostream::sync_with_stdio(false);
  long long n;
  cin >> n;
  a.resize(n);
  for (long long i = 0; i < n; ++i) {
    cin >> a[i];
  }
  graph.resize(n);
  vector<long long> roots;
  for (long long i = 0; i < n; ++i) {
    long long b;
    cin >> b;
    if (b == -1) {
      roots.emplace_back(i);
    } else {
      b--;
      graph[b].emplace_back(i);
    }
  }
  for (long long u : roots) {
    dfs(u);
  }
  cout << ans << '\n';
  reverse(dumbest.begin(), dumbest.end());
  for (long long e : order) {
    cout << e + 1 << ' ';
  }
  for (long long e : dumbest) {
    cout << e + 1 << ' ';
  }
  cout << '\n';
}
