#include <bits/stdc++.h>
using namespace std;
const int N = 200005;
const int inf = 1000 * 1000 * 1000;
const int mod = 1000 * 1000 * 1000 + 7;
mt19937 myrand(chrono::steady_clock::now().time_since_epoch().count());
int n;
long long a[N];
long long res;
vector<int> answ;
vector<int> g[N];
vector<int> after[N];
void rec(int v) {
  answ.push_back(v);
  res += a[v];
  for (int i = 0; i < (int)after[v].size(); i++) {
    int to = after[v][i];
    rec(to);
  }
}
void dfs(int v, int p) {
  for (int i = 0; i < (int)g[v].size(); i++) {
    int to = g[v][i];
    dfs(to, v);
    a[v] += max(a[to], 0ll);
  }
  if (p == -1 || a[v] >= 0) {
    rec(v);
  } else {
    after[p].push_back(v);
  }
}
int main() {
  cin >> n;
  for (int i = 1; i <= n; i++) {
    scanf("%lld", &a[i]);
  }
  vector<int> root;
  for (int i = 1; i <= n; i++) {
    int p;
    scanf("%d", &p);
    if (p == -1) {
      root.push_back(i);
    } else {
      g[p].push_back(i);
    }
  }
  for (int i = 0; i < (int)root.size(); i++) {
    dfs(root[i], -1);
  }
  cout << res << endl;
  for (int i = 0; i < n; i++) {
    printf("%d ", answ[i]);
  }
  cout << endl;
  return 0;
}
