#include <bits/stdc++.h>
using namespace std;
vector<long long> adj[200005];
bool vis[200005] = {false};
long long val[200005];
long long pos[200005];
long long total = 0;
vector<long long> ans, ans1;
void dfs(long long s) {
  vis[s] = true;
  long long i;
  for (i = 0; i < adj[s].size(); i++) {
    if (!vis[adj[s][i]]) dfs(adj[s][i]);
  }
  ans.push_back(s);
}
int main() {
  long long n, i;
  cin >> n;
  map<long long, long long> mpp;
  for (i = 1; i <= n; i++) cin >> val[i];
  for (i = 1; i <= n; i++) {
    cin >> pos[i];
    if (pos[i] != -1) {
      adj[i].push_back(pos[i]);
      mpp[i] = pos[i];
    }
  }
  for (i = 1; i <= n; i++)
    if (!vis[i]) dfs(i);
  for (i = ans.size() - 1; i >= 0; i--) {
    if (val[ans[i]] > 0) {
      if (mpp.count(ans[i])) val[mpp[ans[i]]] += val[ans[i]];
      ans1.push_back(ans[i]);
    }
    total += val[ans[i]];
  }
  for (i = 0; i < ans.size(); i++)
    if (val[ans[i]] <= 0) ans1.push_back(ans[i]);
  cout << total << "\n";
  for (i = 0; i < ans1.size(); i++) cout << ans1[i] << " ";
}
