#include <bits/stdc++.h>
using namespace std;
vector<vector<int>> ad;
vector<bool> vis;
long long ans = 0;
long long a[200001], b[200001];
vector<int> sol0, sol1;
int k = 1;
void dfs(int i) {
  if (vis[i]) {
    return;
  }
  vis[i] = true;
  for (auto c : ad[i]) {
    dfs(c);
  }
  if (b[i] != -1) {
    if (a[i] > 0) {
      a[b[i]] += a[i];
    }
  }
  ans += a[i];
  if (a[i] > 0) {
    sol0.push_back(i);
  } else {
    sol1.push_back(i);
  }
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int n;
  cin >> n;
  ad.assign(n + 1, vector<int>());
  vis.assign(n + 1, false);
  for (int i = 1; i <= n; i++) {
    cin >> a[i];
  }
  for (int i = 1; i <= n; i++) {
    cin >> b[i];
    if (b[i] != -1) {
      ad[b[i]].push_back(i);
    }
  }
  for (int i = 1; i <= n; i++) {
    dfs(i);
  }
  cout << ans << endl;
  for (auto c : sol0) {
    cout << c << " ";
  }
  for (auto it = sol1.rbegin(); it != sol1.rend(); it++) {
    cout << (*it) << " ";
  }
  cout << endl;
}
