#include <bits/stdc++.h>
using namespace std;
long long int t = 0;
long long int n;
long long int a[200005], b[200005];
vector<long long int> v[200005];
long long int et[200005];
long long int col[200005];
void dfs(long long int i) {
  col[i] = 1;
  t++;
  for (long long int j = 0; j < v[i].size(); j++) {
    long long int z = v[i][j];
    if (col[z] == 0) dfs(z);
  }
  t++;
  et[i] = t;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cin >> n;
  for (long long int i = 1; i <= n; i++) cin >> a[i];
  for (long long int i = 1; i <= n; i++) cin >> b[i];
  for (long long int i = 1; i <= n; i++) {
    if (b[i] != -1) {
      v[i].push_back(b[i]);
    }
  }
  for (long long int i = 0; i < n; i++) col[i] = 0;
  for (long long int i = 1; i <= n; i++) {
    if (col[i] == 0) dfs(i);
  }
  pair<long long int, long long int> p[n];
  for (long long int i = 0; i < n; i++) {
    p[i].first = et[i + 1];
    p[i].second = i + 1;
  }
  sort(p, p + n);
  reverse(p, p + n);
  long long int sum = 0;
  vector<int> ans1;
  stack<int> st;
  for (long long int i = 0; i < n; i++) {
    long long int x = p[i].second;
    sum = sum + a[x];
    if (b[x] != -1 && a[x] > 0) {
      a[b[x]] = a[b[x]] + a[x];
      ans1.push_back(x);
    } else if (a[x] < 0)
      st.push(x);
    else
      ans1.push_back(x);
  }
  cout << sum << "\n";
  for (int i = 0; i < ans1.size(); i++) cout << ans1[i] << " ";
  while (!st.empty()) {
    cout << st.top() << " ";
    st.pop();
  }
  return 0;
}
