#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 7;
int n;
long long a[N] = {0}, dp[N];
bool kt[N];
vector<int> edge[N], ans[2];
void dfs(int u) {
  dp[u] = 0;
  for (auto v : edge[u]) {
    dfs(v);
    if (a[v] > 0) {
      ans[0].push_back(v);
      if (u) a[u] += a[v];
    } else
      ans[1].push_back(v);
    dp[u] += dp[v];
  }
  dp[u] += a[u];
}
int main() {
  ios::sync_with_stdio(false), cin.tie(NULL), cout.tie(NULL);
  cin >> n;
  for (int i = (1); i < (n + 1); i++) cin >> a[i];
  for (int i = (1); i < (n + 1); i++) {
    int x;
    cin >> x;
    if (x == -1) x = 0;
    edge[x].push_back(i);
  }
  memset(kt, false, sizeof kt);
  dfs(0);
  cout << dp[0] << '\n';
  for (auto i : ans[0]) cout << i << ' ';
  reverse(ans[1].begin(), ans[1].end());
  for (auto i : ans[1]) cout << i << ' ';
  return 0;
}
