#include <bits/stdc++.h>
using namespace std;
long long int a[200010], b[200010], vis[200010];
vector<long long int> G[200010], ans[2];
long long int Ans;
void dfs(long long int x) {
  vis[x] = 1;
  for (long long int to : G[x]) {
    if (!vis[to]) {
      dfs(to);
    }
  }
  Ans += a[x];
  if (b[x] != -1 and a[x] > 0) {
    a[b[x]] += a[x];
  }
  if (a[x] > 0) {
    ans[0].push_back(x);
  } else {
    ans[1].push_back(x);
  }
}
int main() {
  long long int n;
  cin >> n;
  for (long long int i = 0; i < n; i++) cin >> a[i];
  for (long long int i = 0; i < n; i++) {
    cin >> b[i];
    if (b[i] != -1) {
      b[i]--;
      G[b[i]].push_back(i);
    }
  }
  for (long long int i = 0; i < n; i++) {
    if (!vis[i]) dfs(i);
  }
  cout << Ans << endl;
  reverse(ans[1].begin(), ans[1].end());
  for (long long int i : ans[0]) cout << i + 1 << " ";
  for (long long int i : ans[1]) cout << i + 1 << " ";
  cout << endl;
  return 0;
}
