#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 5;
long long va[N], sum = 0;
int ans[N], in[N], k = 0;
vector<vector<int> > v(N);
long long dp[N];
void dfs(int a, int f) {
  dp[a] = va[a];
  for (int i = 0; i < v[a].size(); i++) {
    int to = v[a][i];
    if (to == f) continue;
    dfs(to, a);
    if (dp[to] > 0) dp[a] += dp[to];
  }
  sum += dp[a];
}
void dfs_(int a, int f) {
  for (int i = 0; i < v[a].size(); i++) {
    int to = v[a][i];
    if (to == f || dp[to] <= 0) continue;
    dfs_(to, a);
  }
  ans[++k] = a;
  for (int i = 0; i < v[a].size(); i++) {
    int to = v[a][i];
    if (to == f || dp[to] > 0) continue;
    dfs_(to, a);
  }
}
int main() {
  ios::sync_with_stdio(false);
  int n;
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> va[i];
  for (int i = 1; i <= n; i++) {
    int b;
    cin >> b;
    if (b == -1) continue;
    v[b].push_back(i);
    in[i]++;
  }
  for (int i = 1; i <= n; i++) {
    if (!in[i]) dfs(i, i), dfs_(i, i);
  }
  cout << sum << endl;
  for (int i = 1; i <= n; i++) {
    if (i != 1) cout << " ";
    cout << ans[i];
  }
  cout << endl;
}
