#include <bits/stdc++.h>
int main() {
  int n;
  scanf("%d", &n);
  std::vector<long long> a(n + 1);
  std::vector<int> b(n + 1);
  std::vector<std::vector<int>> G(n + 1);
  for (int i = 1; i <= n; i++) scanf("%lld", &a[i]);
  for (int i = 1; i <= n; i++) scanf("%d", &b[i]);
  std::vector<bool> vis(n + 1, false);
  for (int i = 1; i <= n; i++)
    if (b[i] != -1) G[b[i]].push_back(i);
  long long ans = 0;
  std::vector<int> p;
  std::function<void(int)> dfs = [&](int u) {
    for (int v : G[u]) {
      dfs(v);
    }
    ans += a[u];
    if (a[u] > 0) {
      p.push_back(u);
      if (b[u] != -1) a[b[u]] += a[u];
      vis[u] = true;
    }
  };
  for (int i = 1; i <= n; i++) {
    if (b[i] == -1) dfs(i);
  }
  std::function<void(int)> dfsc = [&](int u) {
    if (!vis[u]) p.push_back(u);
    for (int v : G[u]) {
      dfsc(v);
    }
  };
  for (int i = 1; i <= n; i++) {
    if (b[i] == -1) dfsc(i);
  }
  printf("%lld\n", ans);
  for (int x : p) printf("%d ", x);
}
