#include <bits/stdc++.h>
using namespace std;
using ll = long long int;
vector<ll> a, c, g[1000000 + 110];
ll val[1000000 + 110];
ll dfs(ll now, ll fa = 0) {
  ll ret = 0;
  for (auto it : g[now])
    if (it != fa) {
      ret += dfs(it, now);
      if (val[it] >= 0) val[now] += val[it];
    }
  if (val[now] >= 0)
    a.push_back(now);
  else
    c.push_back(now);
  return ret + val[now];
}
int main() {
  ll n;
  cin >> n;
  static ll fa[1000000 + 110];
  for (ll i = 1; i <= n; i++) cin >> val[i];
  for (ll i = 1; i <= n; i++) {
    cin >> fa[i];
    if (fa[i] != -1) g[fa[i]].push_back(i);
  }
  ll ret = 0;
  for (ll i = 1; i <= n; i++)
    if (fa[i] == -1) ret += dfs(i);
  cout << ret << "\n";
  for (auto it : a) cout << it << " ";
  reverse(c.begin(), c.end());
  for (auto it : c) cout << it << " ";
  return 0;
}
