#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100005;
int spf[MAXN];
long long fac1[MAXN], fac2[MAXN], inv[MAXN];
long long gcd(long long x, long long y) { return y ? gcd(y, x % y) : x; }
void sieve() {
  spf[1] = 1;
  for (int i = 2; i < MAXN; i++) spf[i] = i;
  for (int i = 4; i < MAXN; i += 2) spf[i] = 2;
  for (int i = 3; i * i < MAXN; i++) {
    if (spf[i] == i)
      for (int j = i * i; j < MAXN; j += i)
        if (spf[j] == j) spf[j] = i;
  }
}
vector<int> getFactorization(int x) {
  vector<int> ret;
  while (x != 1) {
    ret.push_back(spf[x]);
    x = x / spf[x];
  }
  return ret;
}
long long exp(long long n, long long m) {
  long long a = 1;
  while (m) {
    if (m & 1) a = (a * n % 1000000007) % 1000000007;
    m /= 2;
    n = (n * n) % 1000000007;
  }
  return a;
}
void pre() {
  fac1[0] = fac2[0] = inv[1] = 1;
  for (int i = 1; i < MAXN; i++) {
    fac1[i] = (fac1[i - 1] * i) % 1000000007;
    if (i > 1)
      inv[i] =
          (1000000007 -
           ((long long)(1000000007 / i) * inv[1000000007 % i]) % 1000000007) %
          1000000007;
  }
  for (int i = 1; i < MAXN; i++) fac2[i] = (fac2[i - 1] * inv[i]) % 1000000007;
}
long long C(int n, int k) {
  if (n < k) return 0;
  return ((fac1[n] * fac2[n - k] % 1000000007) * fac2[k] % 1000000007);
}
const int nax = 2e5 + 5;
int n;
vector<int> ad[nax], ord;
vector<pair<int, int> > edg;
bool vis[nax];
void dfs(int v) {
  vis[v] = 1;
  for (auto x : ad[v])
    if (!vis[x]) dfs(x);
  ord.push_back(v);
}
int main() {
  ios::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  int t = 1;
  while (t--) {
    cin >> n;
    long long a[n];
    for (int i = 0; i < n; i++) cin >> a[i];
    long long b[n];
    for (int i = 0; i < n; i++) cin >> b[i];
    ord.clear();
    edg.clear();
    for (int i = 0; i < n; i++) {
      ad[i].clear();
      vis[i] = 0;
    }
    for (int i = 0; i < n; i++) {
      if (b[i] != -1) {
        ad[i].push_back(b[i] - 1);
      }
    }
    for (int i = 0; i < n; i++) {
      if (vis[i]) continue;
      dfs(i);
    }
    reverse(ord.begin(), ord.end());
    bool pro[n];
    for (int i = 0; i < n; i++) pro[i] = 0;
    long long sum = 0;
    vector<int> ans;
    for (int i = 0; i < n; i++) {
      if (a[ord[i]] > 0) {
        sum += a[ord[i]];
        pro[ord[i]] = 1;
        ans.push_back(ord[i] + 1);
        if (b[ord[i]] != -1) a[b[ord[i]] - 1] += a[ord[i]];
      } else
        continue;
    }
    for (int i = n - 1; i >= 0; i--) {
      if (!pro[ord[i]]) {
        ans.push_back(ord[i] + 1);
        sum += a[ord[i]];
        pro[ord[i]] = 1;
        if (b[ord[i]] != -1) a[b[ord[i]] - 1] += a[ord[i]];
      }
    }
    cout << sum << "\n";
    for (auto x : ans) cout << x << " ";
    cout << "\n";
  }
  return 0;
}
