#include <bits/stdc++.h>
using namespace std;
long long a[200001], b[200001], dp[200001], ans;
vector<int> graph[200001], vlad;
bool ban[200001];
void dfs(int v) {
  for (int u : graph[v]) dfs(u);
  if (a[v] <= 0 && b[v] != -1) b[v] = -2;
  ans += a[v];
  if (b[v] > -1) {
    a[b[v]] += a[v];
    vlad.push_back(v);
  }
}
void idinahui(int v) {
  if (b[v] == -2) vlad.push_back(v);
  for (int u : graph[v]) idinahui(u);
}
int main() {
  ios::sync_with_stdio(false);
  cin.tie(0);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  vector<int> qq;
  for (int i = 1; i <= n; i++) {
    cin >> b[i];
    if (b[i] != -1)
      graph[b[i]].push_back(i);
    else
      qq.push_back(i);
  }
  for (int it : qq) dfs(it);
  for (int it : qq) vlad.push_back(it);
  cout << ans << "\n";
  for (int it : qq) idinahui(it);
  for (int it : vlad) cout << it << " ";
  return 0;
}
