#include <bits/stdc++.h>
#pragma GCC optimize("Ofast")
#pragma GCC optimize("inline")
#pragma GCC optimize("omit-frame-pointer")
#pragma GCC optimize("unroll-loops")
#pragma comment(linker, "/stack:200000000")
using namespace std;
using namespace std::chrono;
const long long LL_INF = 9223372036854775807;
const double EPS = 1E-9;
const double PI = 3.1415926535897932384626433832795;
template <class T>
void debug(vector<T> vec) {
  for (int i = 0; i < vec.size(); i++) cerr << vec[i] << " ";
  cerr << "\n";
}
template <class T>
void debug(vector<vector<T> > vec) {
  for (int i = 0; i < vec.size(); i++) {
    for (int ii = 0; ii < vec[i].size(); ii++) cerr << vec[i][ii] << " ";
    cerr << "\n";
  }
}
long long a[2 * 100010], b[2 * 100010];
vector<long long> edges[2 * 100010];
vector<long long> order;
vector<long long> trash;
long long dfs(long long n) {
  long long sum = 0;
  for (long long c : edges[n]) {
    sum += dfs(c);
    if (a[c] >= 0) a[n] += a[c];
  }
  if (a[n] < 0) {
    trash.push_back(n);
  } else
    order.push_back(n);
  return sum + a[n];
}
void solve() {
  long long n;
  cin >> n;
  for (int i = 0; i < n; i++) cin >> a[i];
  for (int i = 0; i < n; i++) {
    cin >> b[i];
    if (b[i] > 0) b[i]--;
  }
  long long score = 0;
  for (int i = 0; i < n; i++) {
    if (b[i] != -1) edges[b[i]].push_back(i);
  }
  for (int i = 0; i < n; i++) {
    if (b[i] == -1) score += dfs(i);
  }
  cout << score << "\n";
  for (long long o : order) cout << o + 1 << " ";
  for (int i = trash.size() - 1; i >= 0; i--) cout << trash[i] + 1 << " ";
  cout << "\n";
}
int main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  int testcases = 1;
  int cases = 0;
  while (cases++ != testcases) {
    solve();
  }
}
