#include <bits/stdc++.h>
using namespace std;
const int N = 200010;
int h[N], e[N], ne[N], idx;
int din[N], q[N];
long long a[N];
int n;
void add(int a, int b) {
  e[idx] = b;
  ne[idx] = h[a];
  h[a] = idx++;
}
void topsort() {
  int tt = -1, hh = 0;
  for (int i = 1; i <= n; i++)
    if (din[i] == 0) q[++tt] = i;
  while (tt >= hh) {
    int u = q[hh++];
    for (int i = h[u]; i != -1; i = ne[i]) {
      int j = e[i];
      if (a[u] > 0) a[j] += a[u];
      if (--din[j] == 0) q[++tt] = j;
    }
  }
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie();
  cout.tie(0);
  memset(h, -1, sizeof h);
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  for (int i = 1; i <= n; i++) {
    int b;
    cin >> b;
    if (b != -1) {
      add(i, b);
      din[b]++;
    }
  }
  topsort();
  long long res = 0;
  for (int i = 1; i <= n; i++) res += a[i];
  cout << res << endl;
  for (int i = 0; i < n; i++)
    if (a[q[i]] > 0) cout << q[i] << " ";
  for (int i = n - 1; i >= 0; i--)
    if (a[q[i]] <= 0) cout << q[i] << " ";
  cout << endl;
  return 0;
}
