#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
long long n, a[N], b[N];
long long ans;
vector<int> g[N], pos, neg;
void dfs(int u) {
  for (int v : g[u]) {
    dfs(v);
    if (a[v] > 0) a[u] += a[v];
  }
  if (a[u] >= 0)
    pos.push_back(u);
  else
    neg.push_back(u);
  ans += a[u];
}
int main() {
  ios::sync_with_stdio(0), cin.tie(0);
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  for (int i = 1; i <= n; i++) {
    cin >> b[i];
    if (~b[i]) g[b[i]].push_back(i);
  }
  for (int i = 1; i <= n; i++)
    if (b[i] == -1) dfs(i);
  reverse(neg.begin(), neg.end());
  cout << ans << '\n';
  for (int x : pos) cout << x << " ";
  for (int x : neg) cout << x << " ";
}
