#include <bits/stdc++.h>
using namespace std;
using ll = long long;
const ll inf = INT_MAX - 1;
const ll maxN = 2e5 + 1;
map<ll, ll> occurance;
map<ll, vector<ll>> m;
map<ll, ll> afterTop;
ll order[maxN];
ll arr1[maxN];
ll arr2[maxN];
ll copyArr[maxN];
ll n;
ll top() {
  ll sum = 0;
  queue<ll> q;
  for (auto it = occurance.begin(); it != occurance.end(); it++) {
    if (it->second == 0) {
      q.push(it->first);
    }
  }
  ll cur = 1;
  ll badCur = n;
  while (!q.empty()) {
    ll element = q.front();
    q.pop();
    if (arr1[element] < 0) {
      order[element] = badCur;
      afterTop[badCur] = element;
      badCur--;
      sum += arr1[element];
    } else {
      order[element] = cur;
      afterTop[cur] = element;
      sum += arr1[element];
      if (arr2[element] != -1) {
        arr1[arr2[element]] += arr1[element];
      }
      cur++;
    }
    for (ll i : m[element]) {
      occurance[i]--;
      if (occurance[i] == 0 && order[i] == 0) {
        q.push(i);
      }
    }
  }
  return sum;
}
int main() {
  ios_base::sync_with_stdio(false);
  cin >> n;
  for (ll i = 1; i <= n; i++) {
    cin >> arr1[i];
    copyArr[i] = arr1[i];
    occurance[i] = 0;
  }
  for (ll i = 1; i <= n; i++) {
    cin >> arr2[i];
    if (arr2[i] != -1) occurance[arr2[i]]++;
    m[i].push_back(arr2[i]);
  }
  cout << top() << '\n';
  auto it = afterTop.begin();
  vector<ll> ordering;
  while (it != afterTop.end()) {
    cout << it->second << " ";
    it++;
  }
}
