#include <bits/stdc++.h>
using namespace std;
long long power(long long x, long long y, long long md = 1000000007) {
  long long res = 1;
  x %= md;
  while (y > 0) {
    if (y & 1) res = (res * x) % md;
    x = (x * x) % md;
    y = y >> 1;
  }
  return res % md;
}
long long n;
bool *visited;
vector<long long> path, path1;
void dfs(long long src, vector<long long> &dp, list<long long> *adj) {
  visited[src] = true;
  for (long long child : adj[src]) {
    if (!visited[child]) {
      dfs(child, dp, adj);
      if (dp[child] > 0) dp[src] += dp[child];
    }
  }
  if (dp[src] > 0 && src > 0)
    path.push_back(src);
  else if (dp[src] <= 0 && src > 0)
    path1.push_back(src);
}
signed main() {
  ios_base::sync_with_stdio(false);
  cin.tie(NULL);
  cout.tie(NULL);
  cin >> n;
  vector<long long> a(n + 1), b(n + 1);
  list<long long> *adj = new list<long long>[n + 1];
  visited = new bool[n + 1]{0};
  vector<long long> dp(n + 1, -1);
  for (long long i = 1; i <= n; i++) cin >> a[i], dp[i] = a[i];
  for (long long i = 1; i <= n; i++) {
    cin >> b[i];
    if (b[i] != -1) {
      adj[b[i]].push_back(i);
    } else {
      adj[0].push_back(i);
    }
  }
  dfs(0ll, dp, adj);
  for (long long i = 0; i <= n; i++) visited[i] = false;
  long long ans = 0;
  for (long long i = 1; i <= n; i++) ans += dp[i];
  cout << ans << endl;
  for (long long i : path) cout << i << " ";
  reverse(path1.begin(), path1.end());
  for (long long i : path1) cout << i << " ";
}
