#include <bits/stdc++.h>
using namespace std;
const int S = (1 << 20);
long long vis[S], n, a[S], b[S], indeg[S], ans;
vector<int> result, G[S], roots, to_finish;
void calc(int node) {
  vis[node] = true;
  for (auto e : G[node])
    if (!vis[e]) {
      calc(e);
    }
  if (a[node] < 0)
    to_finish.push_back(node);
  else {
    ans += a[node];
    a[b[node]] += a[node];
    result.push_back(node);
  }
}
int main() {
  ios_base::sync_with_stdio(0);
  cout.tie(0);
  cin.tie(0);
  cin >> n;
  for (int i = 1; i <= n; i++) cin >> a[i];
  for (int i = 1; i <= n; i++) {
    cin >> b[i];
    if (b[i] == -1)
      roots.push_back(i);
    else {
      G[i].push_back(b[i]);
      G[b[i]].push_back(i);
    }
  }
  for (auto e : roots) {
    calc(e);
    reverse(to_finish.begin(), to_finish.end());
    for (auto f : to_finish) {
      ans += a[f];
      result.push_back(f);
    }
    to_finish.clear();
  }
  cout << ans << "\n";
  for (auto e : result) cout << e << " ";
  cout << endl;
  return 0;
}
