#include <bits/stdc++.h>
using namespace std;
long long a[200005];
long long b[200005];
vector<long long> edge[200005];
vector<long long> roots;
vector<bool> visited;
long long max_val[200005];
long long ans = 0;
long long dfs(long long v) {
  visited[v] = true;
  long long ret = 0;
  for (long long next : edge[v]) {
    if (!visited[next]) {
      ret += max(dfs(next), (long long)0);
    }
  }
  ans += ret + a[v];
  return max_val[v] = ret + a[v];
}
void dfs2(long long v) {
  visited[v] = true;
  for (long long next : edge[v]) {
    if (!visited[next]) {
      if (max_val[next] >= 0) {
        dfs2(next);
      }
    }
  }
  printf("%lld ", v);
  for (long long next : edge[v]) {
    if (!visited[next]) {
      dfs2(next);
    }
  }
}
int main() {
  long long n;
  scanf("%lld", &n);
  for (int i = 1; i <= n; i++) {
    scanf("%lld", a + i);
  }
  for (int j = 1; j <= n; j++) {
    long long x;
    scanf("%lld", &x);
    if (x != -1) {
      edge[x].push_back(j);
    } else {
      roots.push_back(j);
    }
  }
  visited = vector<bool>(200005, false);
  for (int i = 0; i < roots.size(); i++) {
    dfs(roots[i]);
  }
  printf("%lld\n", ans);
  visited = vector<bool>(200005, false);
  for (int i = 0; i < roots.size(); i++) {
    dfs2(roots[i]);
  }
  return 0;
}
