#include <bits/stdc++.h>
using namespace std;
const int MAXN = 2.1E5;
long long best[MAXN];
int queOne[MAXN];
int queTwo[MAXN];
vector<int> E[MAXN];
int n, t1, t2;
long long ans;
void find(int u) {
  for (int v : E[u]) find(v), best[u] += best[v] < 0 ? 0 : best[v];
  u ? (ans += best[u], best[u] < 0 ? queTwo[++t2] = u : queOne[++t1] = u) : 0;
}
int main(void) {
  ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
  cin >> n;
  for (int i = 1; i <= n; ++i) cin >> best[i];
  for (int i = 1, v = 0; i <= n; ++i) cin >> v, E[~v ? v : 0].push_back(i);
  for (find(0), cout << ans << '\n'; t2; queOne[++t1] = queTwo[t2--])
    ;
  for (int i = 1; i <= n; ++i) cout << queOne[i] << " \n"[i == n];
  return 0;
}
