#include <bits/stdc++.h>
using namespace std;
vector<int> g[200005];
int in[200005];
void solve() {
  int n;
  cin >> n;
  long long int a[n + 1], b[n + 1];
  for (int i = 1; i <= n; ++i) cin >> a[i];
  for (int i = 1; i <= n; ++i) cin >> b[i];
  for (int i = 1; i <= n; ++i) {
    if (b[i] != -1) {
      g[i].push_back(b[i]);
      in[b[i]]++;
    }
  }
  long long int ans = 0;
  queue<long long int> q;
  vector<long long int> ans1;
  for (int i = 1; i <= n; ++i) {
    if (in[i] == 0) q.push(i);
  }
  vector<long long int> last;
  while (!q.empty()) {
    long long int curr = q.front();
    q.pop();
    for (auto child : g[curr]) {
      in[child]--;
      if (in[child] == 0) q.push(child);
    }
    if (a[curr] < 0) {
      last.push_back(curr);
      continue;
    }
    ans1.push_back(curr);
    if (b[curr] != -1) a[b[curr]] += a[curr];
  }
  reverse(last.begin(), last.end());
  for (auto i : ans1) ans += a[i];
  for (auto i : last) ans += a[i];
  cout << ans << "\n";
  for (auto i : ans1) cout << i << " ";
  for (auto i : last) cout << i << " ";
  cout << "\n";
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int t = 1;
  while (t--) solve();
  return 0;
}
