#include <bits/stdc++.h>
using namespace std;
const long long inf = 1e18;
const long long N = 2e5 + 5;
const long long mod = 1000000007;
long long n;
long long a[N], b[N];
vector<long long> adj[N];
set<pair<long long, long long> > components;
long long par[N];
void dfs(long long x, long long dist) {
  components.insert({-dist, x});
  for (auto it : adj[x]) {
    dfs(it, dist + 1);
  }
}
void testCase() {
  cin >> n;
  for (long long i = 1; i <= n; i++) {
    cin >> a[i];
  }
  for (long long j = 1; j <= n; j++) {
    cin >> b[j];
  }
  for (long long i = 1; i <= n; i++) {
    if (b[i] != -1) {
      adj[b[i]].push_back(i);
    }
  }
  long long ans = 0;
  vector<long long> show;
  for (long long i = 1; i <= n; i++) {
    if (b[i] == -1) {
      components.clear();
      dfs(i, 1);
      vector<pair<long long, long long> > last;
      for (auto it : components) {
        if (a[it.second] >= 0) {
          if (b[it.second] == -1) {
            ans += a[it.second];
            show.push_back(it.second);
          } else {
            ans += a[it.second];
            a[b[it.second]] += a[it.second];
            show.push_back(it.second);
          }
        } else {
          last.push_back({-it.first, it.second});
        }
      }
      sort(last.begin(), last.end());
      for (auto it : last) {
        ans += a[it.second];
        show.push_back(it.second);
      }
    }
  }
  cout << ans << "\n";
  for (auto it : show) {
    cout << it << " ";
  }
  cout << "\n";
}
int32_t main() {
  ios_base::sync_with_stdio(0);
  cin.tie(0);
  cout.tie(0);
  long long t = 1;
  while (t--) testCase();
  return 0;
}
