#include <bits/stdc++.h>
using namespace std;
vector<long long int> primes;
void Sieve(long long int n) {
  vector<bool> prime(n + 1, true);
  for (long long int p = 2; p * p <= n; p++) {
    if (prime[p] == true) {
      for (long long int i = p * p; i <= n; i += p) prime[i] = false;
    }
  }
  for (long long int p = 2; p <= n; p++)
    if (prime[p]) primes.push_back(p);
}
int main() {
  long long int n;
  cin >> n;
  vector<long long int> a(n + 1);
  vector<long long int> b(n + 1);
  for (long long int i = 1; i < n + 1; i++) cin >> a[i];
  for (long long int i = 1; i < n + 1; i++) cin >> b[i];
  vector<long long int> indegree(n + 1, 0);
  vector<long long int> graph[n + 1];
  for (long long int i = 1; i < n + 1; i++) {
    if (b[i] != -1) {
      graph[i].push_back(b[i]);
      indegree[b[i]]++;
    }
  }
  queue<long long int> q;
  for (long long int i = 1; i < n + 1; i++) {
    if (indegree[i] == 0) q.push(i);
  }
  vector<long long int> fw;
  vector<long long int> bw;
  long long int ans = 0;
  while (q.size() != 0) {
    auto p = q.front();
    q.pop();
    ans += a[p];
    if (a[p] > 0)
      fw.push_back(p);
    else
      bw.push_back(p);
    for (auto it : graph[p]) {
      indegree[it]--;
      if (a[p] > 0) a[it] += a[p];
      if (indegree[it] == 0) q.push(it);
    }
  }
  cout << ans << endl;
  for (auto it : fw) cout << it << " ";
  reverse(bw.begin(), bw.end());
  for (auto it : bw) cout << it << " ";
  return 0;
}
