#include <bits/stdc++.h>
using namespace std;
const long long inf = 2e18;
bool prime[1000009];
unordered_map<long long, long long> largest_factor;
void SieveOfEratosthenes(long long n) {
  memset(prime, true, sizeof(prime));
  prime[1] = false;
  for (long long p = 2; p * p <= n; p++) {
    if (prime[p] == true) {
      for (long long i = p * p; i <= n; i += p) {
        prime[i] = false;
        largest_factor[i] = p;
      }
    }
  }
}
long long power(long long x, long long y) {
  if (y == 0)
    return 1;
  else if (y % 2 == 0)
    return power(x, y / 2) * power(x, y / 2);
  else
    return x * power(x, y / 2) * power(x, y / 2);
}
long long mod_power(long long a, long long b, long long m) {
  long long res = 1;
  a %= m;
  while (b) {
    if (b & 1) {
      res = res * a % m;
    }
    a = a * a % m;
    b >>= 1;
  }
  return res;
}
long long vis[200009] = {0};
vector<long long> v[200009];
stack<long long> st;
void dfs(long long s) {
  vis[s] = 1;
  for (auto it : v[s]) {
    if (!vis[it]) dfs(it);
  }
  st.push(s);
}
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(NULL);
  cout.tie(NULL);
  long long n;
  cin >> n;
  long long a[n], b[n];
  for (long long i = 0; i < n; i++) cin >> a[i];
  for (long long i = 0; i < n; i++) {
    cin >> b[i];
    if (b[i] != -1) b[i]--;
  }
  for (long long i = 0; i < n; i++) {
    if (b[i] == -1) continue;
    v[i].push_back(b[i]);
  }
  for (long long i = 0; i < n; i++) {
    if (!vis[i]) {
      dfs(i);
    }
  }
  vector<long long> ord;
  while (!st.empty()) {
    ord.push_back(st.top());
    st.pop();
  }
  vector<long long> ans;
  long long sum = 0;
  for (long long i = 0; i < ord.size(); i++) {
    long long node = ord[i];
    if (a[node] >= 0) {
      if (b[node] != -1) {
        a[b[node]] += a[node];
      }
      ans.push_back(node + 1);
      sum += a[node];
    }
  }
  for (long long i = ord.size() - 1; i >= 0; i--) {
    long long node = ord[i];
    if (a[node] < 0) {
      ans.push_back(node + 1);
      sum += a[node];
    }
  }
  cout << sum << endl;
  for (auto it : ans) cout << it << " ";
  cout << endl;
}
