#include <bits/stdc++.h>
long long aa[200000];
int pp[200000], dd[200000];
long long ans;
int qu[200000], l, r;
void dfs(int i) {
  dd[i] = -1;
  ans += aa[i];
  if (aa[i] > 0)
    qu[l++] = i;
  else
    qu[r--] = i;
  if (pp[i] != -2) {
    if (aa[i] > 0) aa[pp[i]] += aa[i];
    if (--dd[pp[i]] == 0) dfs(pp[i]);
  }
}
int main() {
  int n, i;
  scanf("%d", &n);
  for (i = 0; i < n; i++) scanf("%lld", &aa[i]);
  for (i = 0; i < n; i++) {
    scanf("%d", &pp[i]), pp[i]--;
    if (pp[i] != -2) dd[pp[i]]++;
  }
  l = 0, r = n - 1;
  for (i = 0; i < n; i++)
    if (dd[i] == 0) dfs(i);
  printf("%lld\n", ans);
  for (i = 0; i < n; i++) printf("%d ", qu[i] + 1);
  printf("\n");
  return 0;
}
