#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 10;
vector<int> G[N];
long long a[N], tpa[N], sum;
int b[N];
bool vis[N];
vector<int> ans_p, ans_n;
void dfs(int u) {
  for (int i = 0; i < (int)G[u].size(); i++) {
    int v = G[u][i];
    dfs(v);
  }
  sum += a[u];
  if (a[u] >= 0) {
    ans_p.push_back(u);
    if (b[u] != -1) {
      a[b[u]] += a[u];
    }
  } else {
    ans_n.push_back(u);
  }
}
int main() {
  int n;
  scanf("%d", &n);
  for (int i = 1; i <= n; i++) scanf("%lld", &a[i]);
  for (int i = 1; i <= n; i++) {
    scanf("%d", &b[i]);
    if (b[i] != -1) G[b[i]].push_back(i);
  }
  for (int i = 1; i <= n; i++) {
    if (b[i] == -1) dfs(i);
  }
  printf("%lld\n", sum);
  for (int i = 0; i < (int)ans_p.size(); i++) {
    int v = ans_p[i];
    printf("%d ", v);
  }
  for (int i = (int)ans_n.size() - 1; i >= 0; i--) {
    printf("%d ", ans_n[i]);
  }
  printf("\n");
  return 0;
}
