#include <bits/stdc++.h>
using namespace std;
const int mod = 1e9 + 7;
const int N = 4e5 + 10;
vector<int> ans;
stack<int> tmp;
int b[N], h[N], ne[N], e[N], idx;
long long a[N];
int in[N];
int st[N];
long long res = 0;
void add(int a, int b) { e[idx] = b, ne[idx] = h[a], h[a] = idx++; }
int main() {
  ios::sync_with_stdio(false);
  int n, i;
  cin >> n;
  memset(h, -1, sizeof h);
  for (i = 1; i <= n; i++) {
    cin >> a[i];
  }
  for (i = 1; i <= n; i++) {
    cin >> b[i];
    if (b[i] == -1) continue;
    add(i, b[i]);
    in[b[i]]++;
  }
  queue<int> q;
  for (i = 1; i <= n; i++) {
    if (!in[i]) q.push(i);
  }
  long long res = 0;
  while (q.size()) {
    int t = q.front();
    q.pop();
    res += a[t];
    if (a[t] < 0) {
      tmp.push(t);
    } else {
      ans.push_back(t);
    }
    for (int i = h[t]; i != -1; i = ne[i]) {
      int j = e[i];
      if (a[t] >= 0) a[j] += a[t];
      in[j]--;
      if (!in[j]) q.push(j);
    }
  }
  cout << res << endl;
  for (auto x : ans) {
    cout << x << " ";
  }
  while (tmp.size()) {
    int t = tmp.top();
    tmp.pop();
    cout << t << " ";
  }
  cout << endl;
  return 0;
}
