#include <bits/stdc++.h>
using namespace std;
using namespace std;
const long long mod2 = 998244353;
long long fpow(long long x, long long y, long long p = 1000000007) {
  x = x % p;
  long long sum = 1;
  while (y) {
    if (y & 1) sum = sum * x;
    sum %= p;
    y = y >> 1;
    x = x * x;
    x %= p;
  }
  return sum;
}
long long inv(long long a, long long m = 1000000007) {
  long long c = m;
  long long y = 0, x = 1;
  if (m == 1) return 0;
  while (a > 1) {
    long long q = a / m;
    long long t = m;
    m = a % m, a = t;
    t = y;
    y = x - q * y;
    x = t;
  }
  if (x < 0) x += c;
  return x;
}
vector<long long> adj[200005];
long long a[200005];
long long b[200005];
long long indegree[200005];
int main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long n;
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  for (int i = 1; i <= n; i++) cin >> b[i];
  for (int i = 1; i <= n; i++) {
    if (b[i] != -1) {
      adj[i].push_back(b[i]);
      indegree[b[i]]++;
    }
  }
  long long res = 0;
  vector<long long> r1, r2;
  queue<long long> q;
  for (int i = 1; i <= n; i++) {
    if (indegree[i] == 0) q.push(i);
  }
  while (!q.empty()) {
    long long x = q.front();
    if (a[x] >= 0) {
      res += a[x];
      if (b[x] != -1) a[b[x]] += a[x];
      r1.push_back(x);
    } else
      r2.push_back(x);
    for (auto u : adj[x]) {
      indegree[u]--;
      if (indegree[u] == 0) q.push(u);
    }
    q.pop();
  }
  reverse(r2.begin(), r2.end());
  for (auto u : r2) res += a[u];
  cout << res << "\n";
  for (auto u : r1) cout << u << " ";
  for (auto u : r2) cout << u << " ";
  cout << "\n";
}
