#include <bits/stdc++.h>
using namespace std;
const long long N = 2e5 + 5;
vector<long long> pos[N], in[N], neg[N];
long long a[N];
vector<pair<long long, long long> > ans;
bool stat[N], vis[N];
void dfs(long long u) {
  stat[u] = true;
  for (auto it : in[u]) {
    if (!stat[it]) {
      dfs(it);
      if (a[it] >= 0) {
        a[u] += a[it];
        pos[u].push_back(it);
        neg[it].push_back(u);
      } else {
        neg[u].push_back(it);
        pos[it].push_back(u);
      }
    } else {
      if (a[it] >= 0) {
        a[u] += a[it];
        neg[it].push_back(u);
        pos[u].push_back(it);
      } else {
        pos[it].push_back(u);
        neg[u].push_back(it);
      }
    }
  }
}
void print(long long u) {
  vis[u] = true;
  for (auto it : pos[u]) {
    if (!vis[it]) print(it);
  }
  cout << u << " ";
  for (auto it : neg[u]) {
    if (!vis[it]) {
      print(it);
    }
  }
}
signed main() {
  memset(stat, false, sizeof(stat));
  long long n;
  cin >> n;
  long long b[n + 1];
  for (long long i = 1; i <= n; i++) cin >> a[i];
  for (long long i = 1; i <= n; i++) cin >> b[i];
  for (long long i = 1; i <= n; i++) {
    if (b[i] != -1) {
      in[b[i]].push_back(i);
    }
  }
  for (long long i = 1; i <= n; i++) {
    long long len = in[i].size();
    if (len != 0 and stat[i] == false) {
      dfs(i);
    }
  }
  long long sum = 0;
  for (long long i = 1; i <= n; i++) sum += a[i];
  cout << sum << endl;
  memset(vis, false, sizeof(vis));
  for (long long i = 1; i <= n; i++) {
    long long len = in[i].size();
    if (len != 0 and vis[i] == false) {
      print(i);
    } else if (stat[i] == false) {
      cout << i << " ";
    }
  }
  return 0;
}
