#include <bits/stdc++.h>
using namespace std;
const double pi = acos(-1);
const double eps = 1e-9;
const int mod = 1e9 + 7;
const int mf[] = {0, 0, 1, -1}, mc[] = {1, -1, 0, 0};
const int N = 100005;
mt19937 rng(
    (unsigned int)chrono::steady_clock::now().time_since_epoch().count());
template <typename T>
static T randint(T lo, T hi) {
  return uniform_int_distribution<T>(lo, hi)(rng);
}
template <typename T>
static T randreal(T lo, T hi) {
  return uniform_real_distribution<T>(lo, hi)(rng);
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  rng.seed(time(0));
  int n;
  cin >> n;
  vector<long long> a(n), b(n);
  for (auto &i : a) cin >> i;
  vector<int> d(n);
  for (auto &i : b) {
    cin >> i;
    if (i != -1) {
      i--;
      d[i]++;
    }
  }
  vector<int> ord;
  for (int i = 0; i < n; i++)
    if (d[i] == 0) ord.push_back(i);
  for (int i = 0; i < (int)ord.size(); i++) {
    int u = ord[i];
    if (b[u] != -1) {
      d[b[u]]--;
      if (d[b[u]] == 0) ord.push_back(b[u]);
    }
  }
  assert(ord.size() == n);
  long long ans = 0;
  vector<bool> mark(n);
  vector<int> sol1, sol2;
  for (int i = 0; i < n; i++) {
    int u = ord[i];
    if (a[u] > 0) {
      sol1.push_back(u);
      if (b[u] != -1) a[b[u]] += a[u];
      ans += a[u];
    } else
      sol2.push_back(u);
  }
  for (int i = sol2.size() - 1; i >= 0; i--) {
    int u = sol2[i];
    sol1.push_back(u);
    ans += a[u];
    if (b[u] != -1) a[b[u]] += a[u];
  }
  cout << ans << '\n';
  for (int &i : sol1) cout << i + 1 << " \n"[&i == &sol1.back()];
  return 0;
}
