#include <bits/stdc++.h>
#define ll unsigned long long int

using namespace std;

int main()
{
    iostream::sync_with_stdio(false);
    cin.tie(0);
   ll N;
   cin >> N;
   string s;
   cin >> s;
   ll zero=0,one=0,two=0;
   for(ll i=0;i<N;i++){
    if(s[i]=='0'){
        zero++;
    }else if(s[i]=='1'){
        one++;
    }else{
        two++;
    }
   }

ll sfi,sfilo;
    while(zero<N/3){
            sfi=s.find('1');sfilo=s.find('2');
       if(two>N/3 && one>N/3){

        if(sfi<sfilo){
            s[sfi]='0';
            one--;
            zero++;
        }else{
        s[sfilo]='0';
        two--;
        zero++;
        }
       }else if(two>N/3 && zero<N/3){
    s[sfilo]='0';
    two--;zero++;
    }else if(one>N/3 && zero<N/3){
    s[sfi]='0';
    one--;zero++;
    }
    }
    while(two<N/3){
         sfi=s.find_last_of('1');sfilo=s.find_last_of('0');
       if(zero>N/3 && one>N/3){

        if(sfi>sfilo){
            s[sfi]='2';
            one--;
            two++;
        }else{
        s[sfilo]='2';
        two++;
        zero--;
        }
       }else if(zero>N/3){
       s[sfilo]='2';
        two++;
        zero--;
       }else if(one>N/3){
       s[sfi]='2';
            one--;
            two++;
       }

    }
    while(one<N/3){
            sfi=s.find_last_of('0');sfilo=s.find('2');
        if(two>N/3 && zero>N/3){

            if(sfi>sfilo){
                s[sfi]='1';
                one++;zero--;
            }else{
            s[sfilo]='1';
            two--;one++;
            }
        }else if(zero>N/3){
        s[sfi]='1';
        zero--;one++;
        }else if(two>N/3){
            s[sfilo]='1';
            one++;two--;
        }
    }

cout << s;

}
//5*(5+1)/2


#include <bits/stdc++.h>
#define ll unsigned long long int

using namespace std;

int main()
{
   ll N;
   cin >> N;
   string s;
   cin >> s;
   ll zero=0,one=0,two=0;
   for(ll i=0;i<N;i++){
    if(s[i]=='0'){
        zero++;
    }
    if(s[i]=='1'){
        one++;
    }
    if(s[i]=='2'){
        two++;
    }
   }
for(ll i=0;i<N;i++){
    if(zero<N/3){
       if(two>N/3 && one>N/3){
        if(s.find('1')<s.find('2')){
            s[s.find('1')]='0';
            one--;
            zero++;
        }else{
        s[s.find('2')]='0';
        two--;
        zero++;
        }
       }else if(two>N/3 && zero<N/3){
    s[s.find('2')]='0';
    two--;zero++;
    }else if(one>N/3 && zero<N/3){
    s[s.find('1')]='0';
    one--;zero++;
    }
    }else{
    break;}
}
for(ll i=0;i<N;i++){
    if(two<N/3){
       if(zero>N/3 && one>N/3){
        if(s.find_last_of('1')>s.find_last_of('0')){
            s[s.find_last_of('1')]='2';
            one--;
            two++;
        }else{
        s[s.find_last_of('0')]='2';
        two++;
        zero--;
        }
       }else if(zero>N/3){
       s[s.find_last_of('0')]='2';
        two++;
        zero--;
       }else if(one>N/3){
       s[s.find_last_of('1')]='2';
            one--;
            two++;
       }

    }else{
    break;}
}
for(ll i=0;i<N;i++){
    if(one<N/3){
        if(two>N/3 && zero>N/3){
            if((s.find_last_of('0'))>(s.find('2'))){
                s[s.find_last_of('0')]='1';
                one++;zero--;
            }else{
            s[s.find('2')]='1';
            two--;one++;
            }
        }else if(zero>N/3){
        s[s.find_last_of('0')]='1';
        zero--;one++;
        }else if(two>N/3){
            s[s.find('2')]='1';
            one++;two--;
        }
    }else{

    break;}
}
cout << s;

}

//5*(5+1)/2


#include <bits/stdc++.h>
#define ll unsigned long long int

using namespace std;

int main()
{
    iostream::sync_with_stdio(false);
    cin.tie(0);
   ll N;
   cin >> N;
   string s;
   cin >> s;
   ll zero=0,one=0,two=0;
   for(ll i=0;i<N;i++){
    if(s[i]=='0'){
        zero++;
    }else if(s[i]=='1'){
        one++;
    }else{
        two++;
    }
   }

    while(zero<N/3){
       if(two>N/3 && one>N/3){
        if(s.find('1')<s.find('2')){
            s[s.find('1')]='0';
            one--;
            zero++;
        }else{
        s[s.find('2')]='0';
        two--;
        zero++;
        }
       }else if(two>N/3){
    s[s.find('2')]='0';
    two--;zero++;
    }else{
    s[s.find('1')]='0';
    one--;zero++;
    }
    }
    while(two<N/3){
       if(zero>N/3 && one>N/3){
        if(s.find_last_of('1')>s.find_last_of('0')){
            s[s.find_last_of('1')]='2';
            one--;
            two++;
        }else{
        s[s.find_last_of('0')]='2';
        two++;
        zero--;
        }
       }else if(zero>N/3){
       s[s.find_last_of('0')]='2';
        two++;
        zero--;
       }else{
       s[s.find_last_of('1')]='2';
            one--;
            two++;
       }

    }
    while(one<N/3){
        if(two>N/3 && zero>N/3){
            if((s.find_last_of('0'))>(s.find('2'))){
                s[s.find_last_of('0')]='1';
                one++;zero--;
            }else{
            s[s.find('2')]='1';
            two--;one++;
            }
        }else if(zero>N/3){
        s[s.find_last_of('0')]='1';
        zero--;one++;
        }else{
            s[s.find('2')]='1';
            one++;two--;
        }
    }

cout << s;

}

//5*(5+1)/2


#include <iostream>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;

int main()
{
    int n;
    char str[300009];
    int a = 0,a2;
    int b = 0,b2;
    int c = 0,c2;
    scanf("%d",&n);
    getchar();
    for (int i = 0; i < n; i++){
        scanf("%c",&str[i]);
        if (str[i] == '0')
            a++;
        else if (str[i] == '1')
            b++;
        else
            c++;
    }
    int len = n / 3;
    a2 = a - len;
    b2 = b - len;
    c2 = c - len;
    int cnta = 0,cntb = 0;
    for (int i = 0; i < n; i++){
        if (str[i] == '1')
            cntb++;
        if (str[i] == '0')
            cnta++;
        if (c2 > 0 && str[i] == '2'){
            if (a2 < 0) str[i] = '0',a2++;
            else str[i] = '1',b2++;
            c2--;
        }
        else if (b2 > 0 && str[i] == '1'){
            if (a2 < 0) str[i] = '0',a2++,b2--;
            else if (cntb > len) str[i] = '2',c2++,b2--;
        }
        else if (a2 > 0 && str[i] == '0' && cnta > len){
            if (b2 < 0) str[i] = '1',b2++;
            else str[i] = '2',c2++;
            a2--;
        }
    }
    printf("%s\n",str);
    return 0;
}


#include <iostream>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;

int main()
{
    int n;
    char str[300009];
    int a = 0,a2;
    int b = 0,b2;
    int c = 0,c2;
    scanf("%d",&n);
    getchar();
    for (int i = 0; i < n; i++){
        scanf("%c",&str[i]);
        if (str[i] == '0')
            a++;
        else if (str[i] == '1')
            b++;
        else
            c++;
    }
    int len = n / 3;
    a2 = a - len;
    b2 = b - len;
    c2 = c - len;
    int a1 = 0,b1 = 0;
    for (int i = 0; i < n; i++){
        if (str[i] == '1')
            b1++;
        if (str[i] == '0')
            a1++;
        if (c2 > 0 && str[i] == '2'){
            if (a2 < 0) str[i] = '0',a2++;
            else str[i] = '1',b2++;
            c2--;
        }
        else if (b2 > 0 && str[i] == '1'){
            if (a2 < 0) str[i] = '0',a2++,b2--,b1--;
            else if (b1 > len) str[i] = '2',c2++,b2--;
        }
        else if (a2 > 0 && str[i] == '0' && a1 > len){
            if (b2 < 0) str[i] = '1',b2++;
            else str[i] = '2',c2++;
            a2--;
        }
    }
  /*  for (int i = 0; i < n; i++)             为什么这里改成printf("%s\n",str);   在第六个案例就会输出过多
        printf("%c",str[i]);

        printf("\n");
    */
    printf("%s\n",str);
    return 0;
}
/*
DEBUG 中
输入一个 长度 为 n 的字符串 ，输出 012三种字符都相等的字符串，0 》 1 》 2 按最小次数中最字典序输出
3
121
输出
021

6
000000
输出
001122

6
211200
输出
211200

6
120110
输出
120120
*/


#include <iostream>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;

int main()
{
    int n;
    char str[300009];
    int a = 0,a2;
    int b = 0,b2;
    int c = 0,c2;
    scanf("%d",&n);
    getchar();
    for (int i = 0; i < n; i++){
        scanf("%c",&str[i]);
        if (str[i] == '0')
            a++;
        else if (str[i] == '1')
            b++;
        else
            c++;
    }
    int len = n / 3;
    a2 = a - len;
    b2 = b - len;
    c2 = c - len;
    int a1 = 0,b1 = 0;
    for (int i = 0; i < n; i++){
        if (str[i] == '1')
            b1++;
        if (str[i] == '0')
            a1++;
        if (c2 > 0 && str[i] == '2'){
            if (a2 < 0) str[i] = '0',a2++;
            else str[i] = '1',b2++;
            c2--;
        }
        else if (b2 > 0 && str[i] == '1'){
            if (a2 < 0) str[i] = '0',a2++,b2--,b1--;
            else if (b1 > len) str[i] = '2',c2++,b2--;
        }
        else if (a2 > 0 && str[i] == '0' && a1 > len){
            if (b2 < 0) str[i] = '1',b2++;
            else str[i] = '2',c2++;
            a2--;
        }
    }
    for (int i = 0; i < n; i++)
        printf("%c",str[i]);

        printf("\n");
    return 0;
}
/*
DEBUG 中
输入一个 长度 为 n 的字符串 ，输出 012三种字符都相等的字符串，0 》 1 》 2 按最小次数中最字典序输出
3
121
输出
021

6
000000
输出
001122

6
211200
输出
211200

6
120110
输出
120120
*/


#include <iostream>
#include <cstdio>
#include <queue>
#include <set>
#include <map>
#include <queue>
#include <string>
#include <cstring>
#include <algorithm>
using namespace std;

int main()
{
    int n;
    char str[300009];
    int a = 0,a2;
    int b = 0,b2;
    int c = 0,c2;
    scanf("%d",&n);
    getchar();
    for (int i = 0; i < n; i++){
        scanf("%c",&str[i]);
        if (str[i] == '0')
            a++;
        else if (str[i] == '1')
            b++;
        else
            c++;
    }
    int len = n / 3;
    a2 = a - len;
    b2 = b - len;
    c2 = c - len;
    int a1 = 0,b1 = 0;
    for (int i = 0; i < n; i++){
        if (str[i] == '1')
            b1++;
        if (str[i] == '0')
            a1++;
        if (c2 > 0 && str[i] == '2'){
            if (a2 < 0) str[i] = '0',a2++;
            else str[i] = '1',b2++;
            c2--;
        }
        else if (b2 > 0 && str[i] == '1'){
            if (a2 < 0) str[i] = '0',a2++,b2--;
            else if (b1 > len) str[i] = '2',c2++,b2--;
        }
        else if (a2 > 0 && str[i] == '0' && a1 > len){
            if (b2 < 0) str[i] = '1',b2++;
            else str[i] = '2',c2++;
            a2--;
        }
    }
    printf("%s\n",str);
    return 0;
}


#include<iostream>
#include<vector>
#include<queue>
#include<set>
#include<map>
#include<string>
#include<string.h>
#include<algorithm>
#include<stdlib.h>
#include<ctime>
#include<math.h>
#include<fstream>
#include<stdio.h>
#include<stack>
#include<bitset>
#include<limits.h>
#include<iomanip>  // cout << setprecision(...) <<  fixed;

using namespace std;

void define() {
#define ll long long
#define ld long double
#define vi vector<int>
#define vll vector<ll>
#define vs vector<string>
#define pii pair<int, int>
#define pllll pair<ll, ll>
#define psll pair<string, ll>
#define qi queue<int>
#define qll queue<ll>
#define si set<int>
#define sll set<ll>
#define mulsi multiset<int>
#define mulsll multiset<ll>
#define mulss multiset<string>
#define msi map<string, int>
#define mii map<int, int>
#define ci const int
#define cll const ll
#define cld const ld
#define fi first
#define se second
#define pb push_back
}

cll maxn = 3 * 1e5;
ll n, m;
vll edg[maxn];
int was[maxn];
deque<ll> q1, q2;
ll a[maxn], b[maxn];
ll ans;

void dfs(ll v) {
	was[v] = true;
	for (size_t i = 0; i < edg[v].size(); i++) {
		ll to = edg[v][i];
		if (!was[to]) {
			dfs(to);
		}
	}
	ans += a[v];
	if (b[v] != -1 && a[v] >= 0) {
		a[b[v]] += a[v];
	}
	if (a[v] > 0) {
		q1.push_back(v);
	}
	else {
		q2.push_back(v);
	}
}

int	main() {
	//	freopen("substr.in", "r", stdin);
	//	freopen("substr.out", "w", stdout);
	define();
	ios_base::sync_with_stdio(0);
	cin.tie(0);
	cout.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) {
			edg[b[i]].pb(i);
		}
	}
	ans = 0;
	for (int i = 1; i <= n; i++) {
		if (!was[i]) {
			dfs(i);
		}
	}
	cout << ans << endl;
	while (!q1.empty()) {
		cout << q1.front() << " ";
		q1.pop_front();
	}
	while (!q2.empty()) {
		cout << q2.back() << " ";
		q2.pop_back();
	}

//	system("pause");
}


#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
#include <iostream>
#include <functional>
#include <stack>
#include <queue>
#include <cstdlib>
#include <cstring>
#include <limits.h>
#include <map>
#include <set>
#include <deque>
#include <complex>
#define all(v) (v).begin(),(v).end()
#define sz(v) ((v).size())
using namespace std;
using ll = long long;
using pii = pair<int, int>;
using pll = pair<ll, ll>;
using vi = vector<int>;
using vl = vector<ll>;
using pdd = pair<double, double>;
using pil = pair<int, ll>;

int n;
ll a[200001];
int to[200001];
int indegree[200001];
ll ans = 0;
vi good, bad;

int main() {
	/*#ifndef ONLINE_JUDGE
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
	#endif*/
	ios_base::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);

	cin >> n;
	for (int i = 1; i <= n; i++)
		cin >> a[i];
	for (int i = 1; i <= n; i++) {
		cin >> to[i];
		indegree[to[i]]++;
	}
	queue<int> q;
	for (int i = 1; i <= n; i++)
		if (indegree[i] == 0)
			q.push(i);
	while (!q.empty()) {
		int now = q.front(); q.pop();
		ans += a[now];
		if (a[now] >= 0) {
			good.push_back(now);
			if (to[now] != -1) {
				a[to[now]] += a[now];
				indegree[to[now]]--;
				if (indegree[to[now]] == 0)
					q.push(to[now]);
			}
		}
		else {
			bad.push_back(now);
			if (to[now] != -1) {
				indegree[to[now]]--;
				if (indegree[to[now]] == 0)
					q.push(to[now]);
			}
		}
	}
	cout << ans << "\n";
	for (int x : good)
		cout << x << " ";
	for (int i = bad.size() - 1; i >= 0; i--)
		cout << bad[i] << " ";
}


#include <iostream>
#include <vector>
#include <string>
#include <map>
#include <memory>
#include <set>
#include <algorithm>

using namespace std;
#define MAX 200000

int N;
long long A[MAX], B[MAX], S[MAX];
vector<int> adj[MAX];
int time[MAX];

long long f(int v, int from, int &t) {
	long long res = A[v];
	for (const auto & e : adj[v]) {
		long long x = f(e, v, t);
		if (x > 0)
			res += x;
	}
	S[v] = res;
	time[v] = t;
	t++;
	return res;
}

int main() {
	cin >> N;
	for (int i = 0; i < N; i++)
		cin >> A[i];
	for (int i = 0; i < N; i++) {
		int b;
		cin >> b;
		if (b > 0) {
			b--;
			B[i] = b;
			adj[b].push_back(i);
		}
		else
			B[i] = -1;

	}
	int t = 0;
	for (int i = 0; i < N; i++)
		if (B[i] == -1)
			f(i, -1,t );
	long long res = 0;
	for (int i = 0; i < N; i++)
		res += S[i];
	vector<pair<int, int>> v;
	for (int i = 0; i < N; i++)
		if (S[i] >= 0)
			v.push_back({ time[i], i });
		else
			v.push_back({ MAX * 2 - time[i], i });
	sort(v.begin(), v.end());
	cout << res << "\n";
	for (int i = 0; i < N; i++) {
		if (i > 0)
			cout << " ";
		cout << v[i].second + 1;
	}
	cout << "\n";
	return 0;
}


#include<iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;
using ll = long long;

vector<int> edge[200001];
vector<int> used;
vector<int> order[2];
vector<int> a;
vector<int> b;
ll ans;

void dfs(int x) {

	used[x] = 1;
	for (int to : edge[x]) {
		if (!used[to])
			dfs(to);
	}

	ans += a[x];

	if (b[x] != -1 && a[x] > 0) {
		a[b[x]] += a[x];
	}

	if (a[x] > 0) {
		order[0].push_back(x);
	}
	else {
		order[1].push_back(x);
	}
}
int main() {

	int n;
	cin >> n;

	a = vector<int>(n, 0);
	b = vector<int>(n, 0);
	for (auto& i : a) cin >> i;
	for (int i = 0; i < n; ++i) {
		int x;
		cin >> x;
		if (x != -1) {
			edge[--x].push_back(i);
		}
		b[i] = x;
	}

	used.assign(n, 0);

	for (int i = 0; i < n; ++i) {
		if (!used[i])
			dfs(i);
	}
	cout << ans << "\n";
	for (int i : order[0]) cout << i+1 << " ";

	reverse(order[1].begin(), order[1].end());
	for (int i : order[1]) cout << i+1 << " ";

}


#include<iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;
using ll = long long;

vector<ll> edge[200001];
vector<ll> used;
vector <ll> order[2];
vector<ll> a;
vector<ll> b;
ll ans;

void dfs(int x) {

	used[x] = 1;
	for (int to : edge[x]) {
		if (!used[to])
			dfs(to);
	}

	ans += a[x];

	if (b[x] != -1 && a[x] > 0) {
		a[b[x]] += a[x];
	}

	if (a[x] > 0) {
		order[0].push_back(x);
	}
	else {
		order[1].push_back(x);
	}
}
int main() {

	int n;
	cin >> n;

	a = vector <ll> (n, 0);
	b = vector<ll>(n, 0);
	for (auto& i : a) cin >> i;
	for (int i = 0; i < n; ++i) {
		int x;
		cin >> x;
		if (x != -1) {
			edge[--x].push_back(i);
		}
		b[i] = x;
	}

	used.assign(n, 0);

	for (int i = 0; i < n; ++i) {
		if (!used[i])
			dfs(i);
	}
	cout << ans << "\n";
	for (int i : order[0]) cout << i+1 << " ";

	reverse(order[1].begin(), order[1].end());
	for (int i : order[1]) cout << i+1 << " ";

}


#include<iostream>
#include <vector>
#include <algorithm>
#include <string>

using namespace std;

vector<int> edge[200001];
vector<int> used;
vector<int> order[2];
vector<int> a;
vector<int> b;
int ans;

void dfs(int x) {

	used[x] = 1;
	for (int to : edge[x]) {
		if (!used[to])
			dfs(to);
	}

	ans += a[x];

	if (b[x] != -1 && a[x] > 0) {
		a[b[x]] += a[x];
	}

	if (a[x] > 0) {
		order[0].push_back(x);
	}
	else {
		order[1].push_back(x);
	}
}
int main() {

	int n;
	cin >> n;

	a = vector<int>(n, 0);
	b = vector<int>(n, 0);
	for (auto& i : a) cin >> i;
	for (int i = 0; i < n; ++i) {
		int x;
		cin >> x;
		if (x != -1) {
			edge[--x].push_back(i);
		}
		b[i] = x;
	}

	used.assign(n, 0);

	for (int i = 0; i < n; ++i) {
		if (!used[i])
			dfs(i);
	}
	cout << ans << "\n";
	for (int i : order[0]) cout << i+1 << " ";

	reverse(order[1].begin(), order[1].end());
	for (int i : order[1]) cout << i+1 << " ";

}


#include <iostream>
#include <cstdio>
#include <vector>
#include <cmath>
#include <cstring>
#include <algorithm>
//#define int long long
using namespace std;
typedef long long ll;
const int maxn=2e5+5;
ll ans=0,a[maxn];
int b[maxn];
vector<int>c,d,g[maxn];
void dfs(int x,int fa) {
	for(int i=0;i<g[x].size();i++){
		int v=g[x][i];
		if(v==fa)continue;
		dfs(v,x);
		if(a[v]>=0)a[x]+=a[v];
	}
	if(a[x]>=0)c.push_back(x);
	else d.push_back(x);
	ans+=a[x];
}
int main() {
	int n;
	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])g[b[i]].push_back(i);
	}
	for(int i=1; i<=n; i++)
		if(b[i]==-1)dfs(i,0);
	cout<<ans<<endl;
	for(int i=0;i<c.size();i++)cout<<c[i]<<" ";
	for(int i=d.size()-1;~i;i--)cout<<d[i]<<" ";
	cout<<endl;
}


#include <iostream>
#include <cstdio>
#include <vector>
#include <cmath>
#include <cstring>
#include <algorithm>
//#define int long long
using namespace std;
const int maxn=2e5+5;
int ans=0,a[maxn],b[maxn];
vector<int>c,d,g[maxn];
void dfs(int x,int fa) {
	for(int i=0;i<g[x].size();i++){
		int v=g[x][i];
		if(v==fa)continue;
		dfs(v,x);
		if(a[v]>=0)a[x]+=a[v];
	}
	if(a[x]>=0)c.push_back(x);
	else d.push_back(x);
	ans+=a[x];
}
int main() {
	int n;
	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])g[b[i]].push_back(i);
	}
	for(int i=1; i<=n; i++)
		if(b[i]==-1)dfs(i,0);
	cout<<ans<<endl;
	for(int i=0;i<c.size();i++)cout<<c[i]<<" ";
	for(int i=d.size()-1;~i;i--)cout<<d[i]<<" ";
	cout<<endl;
}


#include <iostream>
#include <iomanip>
#include <algorithm>
#include <vector>
#include <set>
#include <map>
#include <cstring>
#include <string>
#include <queue>
#include <stack>
#include <utility>
#include <tuple>
#include <functional>
#include <unordered_map>
#include <cmath>
#define FAST ios_base::sync_with_stdio(false); cin.tie(nullptr); cout.tie(nullptr);
using namespace std;
typedef long long ll;
typedef pair<int, int> P;
const int MAX = 2e5 + 4;

int n, ind2[MAX], ind[MAX];
ll a[MAX], b[MAX];
vector<int> pg[MAX], g[MAX];

int main() {
	FAST; cin >> n;
	for (int i = 1; i <= n; i++) cin >> a[i];
	for (int i = 1,x; i <= n; i++) {
		cin >> b[i];
		if (b[i] == -1) continue;
		pg[i].push_back(b[i]);
		ind[b[i]]++;
	}

	queue<int> q;
	for (int i = 1; i <= n; i++) if (ind[i] == 0) q.push(i);

	ll ans = 0;
	while (!q.empty()) {
		int u = q.front(); q.pop();
		ans += a[u];
		for (int v : pg[u]) {
			if (a[u] > 0) {
				g[u].push_back(v);
				ind2[v]++;
				a[v] += a[u];
			}
			else {
				g[v].push_back(u);
				ind2[u]++;
			}
			if (--ind[v] == 0) q.push(v);
		}
	}

	cout << ans << '\n';

	for (int i = 1; i <= n; i++) if (ind2[i] == 0) q.push(i);

	while (!q.empty()) {
		int u = q.front(); q.pop();
		cout << u << " ";
		for (int v : g[u]) if (--ind2[v] == 0) q.push(v);
	}
}


#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
typedef long long ll;
const int maxn = 2e5+11;

ll list[maxn];
ll cns[maxn];
int id[maxn];

ll n,ans;
vector<int>G[maxn];
void add(int x,int y){
	G[x].push_back(y);
}
int cnt = 0;
int dfs(int x){
	for(int i=0;i<G[x].size();i++){
		int p = G[x][i];
		dfs(p);
		if(list[p] > 0){
			list[x] += list[p];
		}
	}
	if(list[x] >= 0){
		ans += list[x];
		id[++cnt] = x;
	}
	return 0;
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>list[i];
	}
	for(int i=1;i<=n;i++){
		cin>>cns[i];
		if(cns[i] == -1) continue;
		add(cns[i],i);
	}
	ans = 0;
	for(int i=1;i<=n;i++){
		if(cns[i] == -1){
			dfs(i);
		}
	}
	for(int i=1;i<=n;i++){
		if(list[i] < 0) {
			ans += list[i];
			id[++cnt] = i;
		}
	}
	cout<<ans<<endl;
	for(int i=1;i<=n;i++){
		cout<<id[i]<<" ";
	}
	cout<<endl;

	return 0;
}


#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
typedef long long ll;
const int maxn = 3e5+11;

ll list[maxn];
ll cns[maxn];
int id[maxn];

ll n,ans;
vector<int>G[maxn],a,b;
void add(int x,int y){
	G[x].push_back(y);
}
int cnt = 0;
int dfs(int x){
	for(int i=0;i<G[x].size();i++){
		int p = G[x][i];
		dfs(p);
		if(list[p] > 0){
			list[x] += list[p];
		}
	}
	if(list[x] >= 0){
		ans += list[x];
		a.push_back(x);
	}
	else{
		ans += list[x];
		b.push_back(x);
	}
	return 0;
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>list[i];
	}
	for(int i=1;i<=n;i++){
		cin>>cns[i];
		if(cns[i] == -1) continue;
		add(cns[i],i);
	}
	ans = 0;
	for(int i=1;i<=n;i++){
		if(cns[i] == -1){
			dfs(i);
		}
	}
	cout<<ans<<endl;
	for(int i=0;i<a.size();i++){
		cout<<a[i]<<" ";
	}
	for(int i=0;i<b.size();i++){
		cout<<b[i]<<" ";
	}
	cout<<endl;
	return 0;
}


#include<iostream>
#include<cstring>
#include<vector>
using namespace std;
typedef long long ll;
const int maxn = 3e5+11;

ll list[maxn];
ll cns[maxn];
int id[maxn];

ll n,ans;
vector<int>G[maxn],a,b;
void add(int x,int y){
	G[x].push_back(y);
}
int cnt = 0;
int dfs(int x){
	for(int i=0;i<G[x].size();i++){
		int p = G[x][i];
		dfs(p);
		if(list[p] > 0){
			list[x] += list[p];
		}
	}
	if(list[x] >= 0){
		ans += list[x];
		a.push_back(x);
	}
	return 0;
}
int dfs2(int x){
	if(list[x] < 0) {
		ans += list[x];
		a.push_back(x);
	}
	for(int i=0;i<G[x].size();i++){
		int p = G[x][i];
		dfs2(p);
	}
	return 0;
}
int main(){
	cin>>n;
	for(int i=1;i<=n;i++){
		cin>>list[i];
	}
	for(int i=1;i<=n;i++){
		cin>>cns[i];
		if(cns[i] == -1) continue;
		add(cns[i],i);
	}
	ans = 0;
	for(int i=1;i<=n;i++){
		if(cns[i] == -1){
			dfs(i);
			dfs2(i);
		}
	}
	cout<<ans<<endl;
	for(int i=0;i<a.size();i++){
		cout<<a[i]<<" ";
	}
	cout<<endl;
	return 0;
}


#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <math.h>
#include <queue>
#include <stack>
#include <string>
#include <string.h>
#include <map>
#include <vector>
#include <fstream>
#include <functional>

#define N 202030
#define MOD 1000000007
using namespace std;

int n, m;
int a[N], b[N], f[N];
bool use[N];
vector<int> vec[N];
long long w[N];
vector<int> c;
struct ac {
	int v;
	long long val;
	bool operator()(ac v1, ac v2) {
		if (v1.val >= 0 && v2.val < 0) {
			return 0;
		}
		else if (v1.val < 0 && v2.val >= 0) {
			return 1;
		}
		else if (v1.val >= 0 && v2.val >= 0) {
			return f[v1.v] < f[v2.v];
		}
		else {
			return f[v1.v] > f[v2.v];
		}
	}
};
priority_queue<ac, vector<ac>, ac> que;
void dfs(int u) {
	use[u] = 1;
	for (int v : vec[u]) {
		if (!use[v]) {
			dfs(v);
		}
	}
	f[u] = m++;
}
void solve() {
	int i;
	c.clear();
	while (!que.empty()) {
		que.pop();
	}
	for (i = 1; i <= n; i++) {
		scanf("%d", &a[i]);
		vec[i].clear();
		use[i] = 0;
		w[i] = (long long)a[i];
	}
	for (i = 1; i <= n; i++) {
		scanf("%d", &b[i]);
		if (b[i] != -1) {
			vec[i].push_back(b[i]);
		}
	}
	m = 0;
	for (i = 1; i <= n; i++) {
		if (!use[i]) {
			dfs(i);
		}
	}
	long long ans = 0;
	for (i = 1; i <= n; i++) {
		ac p;
		p.v = i;
		p.val = a[i];
		que.push(p);
		use[i] = 0;
	}
	while (!que.empty()) {
		ac p = que.top();
		que.pop();
		if (p.val != w[p.v] || use[p.v]) {
			continue;
		}
		use[p.v] = 1;
		c.push_back(p.v);
		ans += p.val;
		for (int v : vec[p.v]) {
			if (use[v]) continue;
			w[v] += (long long)w[p.v];
			ac q;
			q.v = v;
			q.val = w[v];
			que.push(q);
		}
	}
	printf("%lld\n", ans);
	for (int v : c) {
		printf("%d ", v);
	}
	printf("\n");
}

int main() {
	int tc;
	//freopen("c:\\data\\cin.txt", "r", stdin);
	//scanf("%d", &tc);
	//while (tc--) {
	while (scanf("%d", &n) != EOF) {
		solve();
	}
	return 0;
}


#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <math.h>
#include <queue>
#include <stack>
#include <string>
#include <string.h>
#include <map>
#include <vector>
#include <fstream>
#include <functional>

#define N 202030
#define MOD 1000000007
using namespace std;

int n, m;
int a[N], b[N], f[N];
bool use[N];
vector<int> vec[N];
long long w[N];
vector<int> c;
struct ac {
	int v;
	long long val;
	bool operator()(ac v1, ac v2) {
		if (v1.val >= 0 && v2.val < 0) {
			return 0;
		}
		else if (v1.val < 0 && v2.val >= 0) {
			return 1;
		}
		else if (v1.val >= 0 && v2.val >= 0) {
			return f[v1.v] < f[v2.v];
		}
		else {
			return f[v1.v] > f[v2.v];
		}
	}
};
priority_queue<ac, vector<ac>, ac> que;
void dfs(int u) {
	use[u] = 1;
	for (int v : vec[u]) {
		if (!use[v]) {
			dfs(v);
		}
	}
	f[u] = m++;
}
void solve() {
	int i;
	c.clear();
	while (!que.empty()) {
		que.pop();
	}
	for (i = 1; i <= n; i++) {
		scanf("%d", &a[i]);
		vec[i].clear();
		use[i] = 0;
		w[i] = (long long)a[i];
	}
	for (i = 1; i <= n; i++) {
		scanf("%d", &b[i]);
		if (b[i] != -1) {
			vec[i].push_back(b[i]);
		}
	}
	m = 0;
	for (i = 1; i <= n; i++) {
		if (!use[i]) {
			dfs(i);
		}
	}
	long long ans = 0;
	for (i = 1; i <= n; i++) {
		ac p;
		p.v = i;
		p.val = a[i];
		que.push(p);
		use[i] = 0;
	}
	while (!que.empty()) {
		ac p = que.top();
		que.pop();
		if (p.val != w[p.v]) {
			continue;
		}
		use[p.v] = 1;
		c.push_back(p.v);
		ans += p.val;
		for (int v : vec[p.v]) {
			if (use[v]) continue;
			w[v] += (long long)w[p.v];
			ac q;
			q.v = v;
			q.val = w[v];
			que.push(q);
		}
	}
	printf("%lld\n", ans);
	for (int v : c) {
		printf("%d ", v);
	}
	printf("\n");
}

int main() {
	int tc;
	//freopen("c:\\data\\cin.txt", "r", stdin);
	//scanf("%d", &tc);
	//while (tc--) {
	while (scanf("%d", &n) != EOF) {
		solve();
	}
	return 0;
}


#define _CRT_SECURE_NO_WARNINGS
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <algorithm>
#include <math.h>
#include <queue>
#include <stack>
#include <string>
#include <string.h>
#include <map>
#include <vector>
#include <fstream>
#include <functional>

#define N 202030
#define MOD 1000000007
using namespace std;

int n, m;
int a[N], b[N], f[N];
bool use[N];
vector<int> vec[N];
long long w[N];
vector<int> c;
struct ac {
	int v;
	long long w;
	bool operator()(ac v1, ac v2) {
		if (a[v1.v] >= 0 && a[v2.v] < 0) {
			return 0;
		}
		else if (a[v1.v] < 0 && a[v2.v] >= 0) {
			return 1;
		}
		else if (a[v1.v] >= 0 && a[v2.v] >= 0) {
			return f[v1.v] < f[v2.v];
		}
		else {
			return f[v1.v] > f[v2.v];
		}
	}
};
priority_queue<ac, vector<ac>, ac> que;
void dfs(int u) {
	use[u] = 1;
	for (int v : vec[u]) {
		if (!use[v]) {
			dfs(v);
		}
	}
	f[m++] = u;
}
void solve() {
	int i;
	c.clear();
	while (!que.empty()) {
		que.pop();
	}
	for (i = 1; i <= n; i++) {
		scanf("%d", &a[i]);
		vec[i].clear();
		use[i] = 0;
		w[i] = (long long)a[i];
	}
	for (i = 1; i <= n; i++) {
		scanf("%d", &b[i]);
		if (b[i] != -1) {
			vec[i].push_back(b[i]);
		}
	}
	m = 0;
	for (i = 1; i <= n; i++) {
		if (!use[i]) {
			dfs(i);
		}
	}
	long long ans = 0;
	for (i = 1; i <= n; i++) {
		ac p;
		p.v = i;
		p.w = a[i];
		que.push(p);
		use[i] = 0;
	}
	while (!que.empty()) {
		ac p = que.top();
		que.pop();
		if (p.w != w[p.v]) {
			continue;
		}
		use[p.v] = 1;
		c.push_back(p.v);
		ans += p.w;
		for (int v : vec[p.v]) {
			if (use[v]) continue;
			w[v] += (long long)w[p.v];
			ac q;
			q.v = v;
			q.w = w[v];
			que.push(q);
		}
	}
	printf("%lld\n", ans);
	for (int v : c) {
		printf("%d ", v);
	}
	printf("\n");
}

int main() {
	int tc;
	//freopen("c:\\data\\cin.txt", "r", stdin);
	//scanf("%d", &tc);
	//while (tc--) {
	while (scanf("%d", &n) != EOF) {
		solve();
	}
	return 0;
}


#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <cmath>
#include <map>
#include <set>

#define INF 987654321

using namespace std;

typedef pair<int, int> pi;
typedef pair<int, pair<int, int>>ppi;
typedef unsigned int ui;
typedef long long ll;

int dx[] = { -1, 1, 0, 0, -1, -1, 1, 1 };
int dy[] = { 0, 0, -1, 1, -1, 1, -1, 1 };

//----------------------------------------------------

int main(void) {

	ios::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);

	int n;
	ll sum = 0;
	cin >> n;
	vector<ll>a(n);
	vector<int>b(n);
	vector<int>indegree(n, 0);
	set<int>s;

	vector<int>ans[2];

	for (int i = 0; i < n; i++)cin >> a[i];

	for (int i = 0; i < n; i++) {
		cin >> b[i];
		--b[i];
		if (b[i] == -2)continue;
		indegree[b[i]]++;
	}

	for (int i = 0; i < n; i++) {
		if (indegree[i] == 0)s.insert(i);
	}

	while (!s.empty()) {
		int now = *s.begin();
		s.erase(s.begin());
		int next = b[now];
		sum += a[now];
		if (a[now] >= 0) {
			if (next >= 0)a[next] += a[now];
			ans[0].push_back(now);
		}
		else {
			ans[1].push_back(now);
		}
		if (next >= 0) {
			if (--indegree[next] == 0)s.insert(next);
		}
	}

	cout << sum << '\n';
	for (int i : ans[0])cout << i + 1 << ' ';

	reverse(ans[1].begin(), ans[1].end());

	for (int i : ans[1])cout << i + 1 << ' ';
	cout << '\n';

}


#include <iostream>
#include <algorithm>
#include <vector>
#include <string>
#include <stack>
#include <queue>
#include <deque>
#include <cmath>
#include <map>
#include <set>

#define INF 987654321

using namespace std;

typedef pair<int, int> pi;
typedef pair<int, pair<int, int>>ppi;
typedef unsigned int ui;
typedef long long ll;

int dx[] = { -1, 1, 0, 0, -1, -1, 1, 1 };
int dy[] = { 0, 0, -1, 1, -1, 1, -1, 1 };

//----------------------------------------------------

int main(void) {

	ios::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);

	int n;
	ll ans = 0;
	cin >> n;
	vector<ll>a(n);
	vector<int>b(n);
	vector<int>inDegree(n, 0);

	for (int i = 0; i < n; i++)cin >> a[i];

	for (int i = 0; i < n; i++) {
		cin >> b[i];
		if (--b[i] >= 0)inDegree[b[i]]++;
	}
	queue<int>q;
	for (int i = 0; i < n; i++) {
		if (inDegree[i] == 0)q.push(i);
	}
	queue<int>pos;
	stack<int>neg;

	while (!q.empty()) {
		int now = q.front(); q.pop();
		ans += a[now];
		if (a[now] >= 0) {
			pos.push(now);
			if (b[now] >= 0) {
				a[b[now]] += a[now];
				if(--inDegree[b[now]] == 0)q.push(b[now]);
			}
		}
		else {
			neg.push(now);
			if (b[now] >= 0 && --inDegree[b[now]] == 0) {
				q.push(b[now]);
			}
		}
	}

	cout << ans << '\n';
	while (!pos.empty()) {
		cout << pos.front() + 1 << ' ';
		pos.pop();
	}
	while (!neg.empty()) {
		cout << neg.top() + 1 << ' ';
		neg.pop();
	}
	cout << '\n';

	return 0;

}


#include<iostream>
#include<algorithm>
#include<string>
#include<vector>
#include<map>
#include<set>
#include<queue>
#include<cmath>
#include<stack>
#include<chrono>
#include<random>
#include<cerrno>
#include<cfenv>

typedef long long int lli;
typedef long long ll;
typedef double long dl;
using namespace std;

const int mod = 1000000007;
const dl pi = std::acos(-1);

ll gcd(ll a, ll b) {
	if (!b) {
		return a;
	}
	return gcd(b, a % b);
}

ll gcdE(ll a, ll b, ll* x, ll* y) {
	if (!a) {
		*x = 0;
		*y = 1;
		return b;
	}
	ll x1, y1;
	ll _gcd = gcdE(b % a, a, &x1, &y1);
	*x = y1 - (b / a) * x1;
	*y = x1;
	return _gcd;
}

ll power(ll x, ll y) {
	ll res = 1;
	while (y) {
		if (y & 1) {
			res = (res * x) % mod;
		}
		y >>= 1;
		x = (x * x) % mod;
	}
	return res;
}

ll inverse(ll x) {
	return power(x, mod - 2);
}

ll res = 0;

vector<int>a(200005), p(200005, -1);
vector<int>adj[200005];
vector<int>nodes, nodes2;

ll dfs(int c) {
	ll custom = a[c];
	for (int x : adj[c]) {
		custom += dfs(x);
	}
	res += custom;
	if (custom >= 0) {
		nodes.push_back(c);
	}
	else {
		nodes2.push_back(c);
	}
	return max(custom, 0LL);
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
	int t;
	//cin >> t;
	t = 1;
	while (t--) {
		int n;
		cin >> n;
		for (int i = 1; i <= n; i += 1) {
			cin >> a[i];
		}
		int b;
		for (int i = 1; i <= n; i += 1) {
			cin >> b;
			if (~b) {
				adj[b].push_back(i);
				p[i] = b;
			}
		}
		for (int i = 1; i <= n; i += 1) {
			if (p[i] == -1) {
				dfs(i);
			}
		}
		cout << res << "\n";
		for (int x : nodes) {
			cout << x << " ";
		}
		reverse(nodes2.begin(), nodes2.end());
		for (int x : nodes2) {
			cout << x << " ";
		}
		cout << "\n";
	}
}


#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <set>
#include <map>
#include <vector>
#include <queue>
#include <algorithm>

using namespace std;

const int maxN = 201000;

vector<int> g[maxN];
long long a[maxN];
int b[maxN];
int used[maxN];
vector<int> tpsort;

void dfs(int v) {
	used[v] = 1;

	for (int i = 0; i < g[v].size(); ++i) {
		int to = g[v][i];
		if (!used[to]) {
			dfs(g[v][i]);
		}
	}
	tpsort.push_back(v);
}

void solve() {
	int n;
	cin >> n;
	for (int i = 0; i < n; ++i) {
		cin >> a[i];
	}

	for (int i = 0; i < n; ++i) {
		cin >> b[i];
		if (b[i] != -1) {
			--b[i];
		}
		if (b[i] == i) {
			b[i] = -1;
		}
		if (b[i] != -1) {
			g[i].push_back(b[i]);
		}
	}

	for (int i = 0; i < n; ++i) {
		if (!used[i]) {
			dfs(i);
		}
	}

	reverse(tpsort.begin(), tpsort.end());

	long long ans = 0;

	vector<int> res;

	for (int i = 0; i < n; ++i) {
		used[i] = 0;
	}
	for (int i = 0; i < tpsort.size(); ++i) {
		int v = tpsort[i];
		if (a[v] > 0) {
			ans += a[v];
			res.push_back(v);
			if (b[v] != -1) {
				a[b[v]] += a[v];
			}
			used[v] = 1;
		}
	}

	reverse(tpsort.begin(), tpsort.end());
	for (int i = 0; i < tpsort.size(); ++i) {
		int v = tpsort[i];
		if (!used[v]) {
			ans += a[v];
			res.push_back(v);
		}
	}

	cout << ans << endl;
	for (int i = 0; i < res.size(); ++i) {
		cout << res[i] + 1 << " ";
	}
	cout << endl;
}

int main() {
	//freopen("input.txt", "r", stdin);
	//freopen("output.txt", "w", stdout);
	ios_base::sync_with_stdio(false);

	int t;
	//cin >> t;
	t = 1;

	for (int tt = 0; tt < t; ++tt) {
		solve();
	}

	return 0;
}


#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
//#include <tchar.h>
//#include <intrin.h>

#define F first
#define S second
#define LL long long
#define MOD 1000000007
#define INF 1000000000
#define LINF 1000000000000000000

using namespace std;

const int N = 2e5 + 10;

LL a[N];
LL b[N];
bool p[N];
int indegree[N];
queue<int>que;
vector<int>ans;
vector<int>adj[N];

int main()
{
	/*freopen("haircut.in", "r", stdin);
	freopen("haircut.out", "w", stdout);*/

	int n;
	scanf("%d", &n);

	for (int i = 1;i <= n;i++)
		scanf("%lld", &a[i]);

	for (int i = 1;i <= n;i++)
		scanf("%lld", &b[i]);

	for (int i = 1;i <= n;i++)
		if (b[i] == -1)continue;
		else {
			adj[i].push_back(b[i]);
			indegree[b[i]]++;
		}

		for (int i = 1;i <= n;i++)
			if (!indegree[i] && a[i] >= 0)que.push(i);

	LL ans1 = 0;
	while (!que.empty()) {
		int t = que.front();
		que.pop();
		ans.push_back(t);

		p[t] = 1;
		ans1 += a[t];
		if (b[t] + 1)
		a[b[t]] += a[t];

		for (auto x : adj[t]) {
			indegree[x]--;
			if (!indegree[x] && a[x] >= 0)que.push(x);
		}
	}

	for (int i = 1;i <= n;i++)
		adj[i].clear();

	for (int i = 1;i <= n;i++)
		if (p[i] || b[i] == -1 || p[b[i]])continue;
		else {
			adj[b[i]].push_back(i);
			indegree[i]++;
		}

	for (int i = 1;i <= n;i++)
		if (!p[i] && !indegree[i])que.push(i);

	while (!que.empty()) {
		int t = que.front();
		que.pop();
		ans.push_back(t);

		p[t] = 1;
		ans1 += a[t];
		if (b[t] + 1)
			a[b[t]] += a[t];

		for (auto x : adj[t]) {
			indegree[x]--;
			if (!indegree[x])que.push(x);
		}
	}

	for (int i = 1;i <= n;i++)
		if (!p[i])ans.push_back(i), ans1 += a[i];

	printf("%lld\n", ans1);
	for (auto x : ans)
		printf("%d ", x);

	cin >> n;
}


#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
//#include <tchar.h>
//#include <intrin.h>

#define F first
#define S second
#define LL long long
#define MOD 1000000007
#define INF 1000000000
#define LINF 1000000000000000000

using namespace std;

const int N = 2e5 + 10;

LL a[N];
LL b[N];
bool p[N];
int indegree[N];
queue<int>que;
vector<int>ans;
vector<int>adj[N];

int main()
{
	/*freopen("haircut.in", "r", stdin);
	freopen("haircut.out", "w", stdout);*/

	int n;
	scanf("%d", &n);

	for (int i = 1;i <= n;i++)
		scanf("%lld", &a[i]);

	for (int i = 1;i <= n;i++)
		scanf("%lld", &b[i]);

	for (int i = 1;i <= n;i++)
		if (b[i] == -1)continue;
		else
		if (a[i] >= 0) {
			adj[i].push_back(b[i]);
			indegree[b[i]]++;
		}

	for (int i = 1;i <= n;i++)
		if (!indegree[i] && a[i] >= 0)que.push(i);
		else if (!indegree[i] && a[i] < 0)p[i] = 1;

	while (!que.empty()) {
		int t = que.front();
		que.pop();
		ans.push_back(t);

		for (auto x : adj[t]) {
			indegree[x]--;
			if (!indegree[x])que.push(x);
		}
	}

	for (int i = 1;i <= n;i++)
		if (p[i])ans.push_back(i);

	LL ans1 = 0;
	for (auto x : ans) {
		ans1 += a[x];
		if (b[x] != -1)a[b[x]] += a[x];
	}

	printf("%lld\n", ans1);
	for (auto x : ans)
		printf("%d ", x);

	cin >> n;
}


#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
//#include <tchar.h>
//#include <intrin.h>

#define F first
#define S second
#define LL long long
#define MOD 1000000007
#define INF 1000000000
#define LINF 1000000000000000000

using namespace std;

const int N = 2e5 + 10;

LL a[N];
LL b[N];
bool p[N];
int indegree[N];
queue<int>que;
vector<int>ans;
vector<int>adj[N];

int main()
{
	/*freopen("haircut.in", "r", stdin);
	freopen("haircut.out", "w", stdout);*/

	int n;
	scanf("%d", &n);

	for (int i = 1;i <= n;i++)
		scanf("%lld", &a[i]);

	for (int i = 1;i <= n;i++)
		scanf("%lld", &b[i]);

	for (int i = 1;i <= n;i++)
		if (b[i] == -1)continue;
		else
		if (a[i] >= 0) {
			adj[i].push_back(b[i]);
			indegree[b[i]]++;
		}
		else {
			adj[b[i]].push_back(i);
			indegree[i]++;
		}

	for (int i = 1;i <= n;i++)
		if (!indegree[i])que.push(i);

	LL ans1 = 0;
	while (!que.empty()) {
		int t = que.front();
		que.pop();
		ans.push_back(t);

		p[t] = 1;
		ans1 += a[t];
		if (b[t] + 1)
		a[b[t]] += a[t];

		for (auto x : adj[t]) {
			indegree[x]--;
			if (!indegree[x])que.push(x);
		}
	}

	for (int i = 1;i <= n;i++)
		if (!p[i])ans.push_back(i), ans1 += a[i];

	printf("%lld\n", ans1);
	for (auto x : ans)
		printf("%d ", x);

	cin >> n;
}


#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
//#include <tchar.h>
//#include <intrin.h>

#define F first
#define S second
#define LL long long
#define MOD 1000000007
#define INF 1000000000
#define LINF 1000000000000000000

using namespace std;

const int N = 2e5 + 10;

LL a[N];
LL b[N];
bool p[N];
int indegree[N];
queue<int>que;
vector<int>ans;
vector<int>adj[N];

int main()
{
	/*freopen("haircut.in", "r", stdin);
	freopen("haircut.out", "w", stdout);*/

	int n;
	scanf("%d", &n);

	for (int i = 1;i <= n;i++)
		scanf("%lld", &a[i]);

	for (int i = 1;i <= n;i++)
		scanf("%lld", &b[i]);

	for (int i = 1;i <= n;i++)
		if (b[i] == -1)continue;
		else
		if (a[i] >= 0) {
			adj[i].push_back(b[i]);
			indegree[b[i]]++;
		}

	for (int i = 1;i <= n;i++)
		if (!indegree[i] && a[i] >= 0)que.push(i);
		else if (!indegree[i] && a[i] < 0)p[i] = 1;

	while (!que.empty()) {
		int t = que.front();
		que.pop();
		ans.push_back(t);

		for (auto x : adj[t]) {
			indegree[x]--;
			if (!indegree[x] && a[x] >= 0)que.push(x);
			else if (!indegree[x] && a[x] < 0)p[x] = 1;
		}
	}

	for (int i = 1;i <= n;i++)
		if (p[i])ans.push_back(i);

	LL ans1 = 0;
	for (auto x : ans) {
		ans1 += a[x];
		if (b[x] != -1)a[b[x]] += a[x];
	}

	printf("%lld\n", ans1);
	for (auto x : ans)
		printf("%d ", x);

	cin >> n;
}


#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
//#include <tchar.h>
//#include <intrin.h>

#define F first
#define S second
#define LL long long
#define MOD 1000000007
#define INF 1000000000
#define LINF 1000000000000000000

using namespace std;

const int N = 2e5 + 10;

LL a[N];
LL b[N];
bool p[N];
int indegree[N];
queue<int>que;
vector<int>ans;
vector<int>adj[N];

int main()
{
	/*freopen("haircut.in", "r", stdin);
	freopen("haircut.out", "w", stdout);*/

	int n;
	scanf("%d", &n);

	for (int i = 1;i <= n;i++)
		scanf("%lld", &a[i]);

	for (int i = 1;i <= n;i++)
		scanf("%lld", &b[i]);

	for (int i = 1;i <= n;i++)
		if (b[i] == -1)continue;
		else
		if (a[i] >= 0) {
			adj[i].push_back(b[i]);
			indegree[b[i]]++;
		}
		else {
			adj[b[i]].push_back(i);
			indegree[i]++;
		}

	for (int i = 1;i <= n;i++)
		if (!indegree[i])que.push(i);

	LL ans1 = 0;
	while (!que.empty()) {
		int t = que.front();
		que.pop();
		ans.push_back(t);

		p[t] = 1;
		ans1 += a[t];
		if (b[t] + 1)
		a[b[t]] += a[t];

		for (auto x : adj[t]) {
			indegree[x]--;
			if (!indegree[x] && a[b[t]] >= 0)que.push(x);
		}
	}

	for (int i = 1;i <= n;i++)
		if (!p[i])ans.push_back(i), ans1 += a[i];

	printf("%lld\n", ans1);
	for (auto x : ans)
		printf("%d ", x);

	cin >> n;
}


#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
//#include <tchar.h>
//#include <intrin.h>

#define F first
#define S second
#define LL long long
#define MOD 1000000007
#define INF 1000000000
#define LINF 1000000000000000000

using namespace std;

const int N = 2e5 + 10;

LL a[N];
LL b[N];
int indegree[N];
queue<int>que;
vector<int>ans[2];
vector<int>adj[N];

int main()
{
	/*freopen("haircut.in", "r", stdin);
	freopen("haircut.out", "w", stdout);*/

	int n;
	scanf("%d", &n);

	for (int i = 1;i <= n;i++)
		scanf("%lld", &a[i]);

	for (int i = 1;i <= n;i++)
		scanf("%lld", &b[i]);

	for (int i = 1;i <= n;i++)
		if (b[i] == -1)continue;
		else {
			adj[i].push_back(b[i]);
			indegree[b[i]]++;
		}

		for (int i = 1;i <= n;i++)
			if (!indegree[i])que.push(i);

		LL ans1 = 0;
		while (!que.empty()) {
			int t = que.front();
			que.pop();
			ans1 += a[t];

			if (a[t] > 0 && b[t] != -1) {
				ans[0].push_back(t);
				a[b[t]] += a[t];
			}
			else
				ans[1].push_back(t);

			for (auto x : adj[t]) {
				indegree[x]--;
				if (!indegree[x])que.push(x);
			}
		}

		printf("%lld\n", ans1);

		for (auto x : ans[0])
			printf("%d ", x);

		reverse(ans[1].begin(), ans[1].end());
		for (auto x : ans[1])
			printf("%d ", x);

	cin >> n;
}


#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
//#include <tchar.h>
//#include <intrin.h>

#define F first
#define S second
#define LL long long
#define MOD 1000000007
#define INF 1000000000
#define LINF 1000000000000000000

using namespace std;

const int N = 2e5 + 10;

LL a[N];
LL b[N];
int indegree[N];
queue<int>que;
vector<int>ans;
vector<int>adj[N];

int main()
{
	/*freopen("haircut.in", "r", stdin);
	freopen("haircut.out", "w", stdout);*/

	int n;
	scanf("%d", &n);

	for (int i = 1;i <= n;i++)
		scanf("%lld", &a[i]);

	for (int i = 1;i <= n;i++)
		scanf("%lld", &b[i]);

	for (int i = 1;i <= n;i++)
		if (b[i] == -1)continue;
		else
		if (a[i] >= 0) {
			adj[i].push_back(b[i]);
			indegree[b[i]]++;
		}
		else indegree[i] = 1;

	for (int i = 1;i <= n;i++)
		if (!indegree[i])que.push(i);

	while (!que.empty()) {
		int t = que.front();
		que.pop();
		ans.push_back(t);

		for (auto x : adj[t]) {
			indegree[x]--;
			if (!indegree[x])que.push(x);
		}
	}

	for (int i = 1;i <= n;i++)
		if (indegree[i])ans.push_back(i);

	LL ans1 = 0;
	for (auto x : ans) {
		ans1 += a[x];
		if (b[x] != -1)a[b[x]] += a[x];
	}

	printf("%lld\n", ans1);
	for (auto x : ans)
		printf("%d ", x);

	cin >> n;
}


#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
//#include <tchar.h>
//#include <intrin.h>

#define F first
#define S second
#define LL long long
#define MOD 1000000007
#define INF 1000000000
#define LINF 1000000000000000000

using namespace std;

const int N = 2e5 + 10;

LL a[N];
LL b[N];
bool p[N];
int indegree[N];
queue<int>que;
vector<int>ans;
vector<int>adj[N];

int main()
{
	/*freopen("haircut.in", "r", stdin);
	freopen("haircut.out", "w", stdout);*/

	int n;
	scanf("%d", &n);

	for (int i = 1;i <= n;i++)
		scanf("%lld", &a[i]);

	for (int i = 1;i <= n;i++)
		scanf("%lld", &b[i]);

	for (int i = 1;i <= n;i++)
		if (b[i] == -1)continue;
		else
		if (a[i] >= 0) {
			adj[i].push_back(b[i]);
			indegree[b[i]]++;
		}
		else {
			adj[b[i]].push_back(i);
			indegree[i]++;
		}

	for (int i = 1;i <= n;i++)
		if (!indegree[i])que.push(i);

	LL ans1 = 0;
	while (!que.empty()) {
		int t = que.front();
		que.pop();
		ans.push_back(t);

		p[t] = 1;
		ans1 += a[t];
		if (b[t] + 1)
		a[b[t]] += a[t];

		for (auto x : adj[t]) {
			indegree[x]--;
			if (!indegree[x] && a[x] >= 0)que.push(x);
		}
	}

	for (int i = 1;i <= n;i++)
		if (!p[i])ans.push_back(i), ans1 += a[i];

	printf("%lld\n", ans1);
	for (auto x : ans)
		printf("%d ", x);

	cin >> n;
}


#define _CRT_SECURE_NO_WARNINGS

#include <stdio.h>
#include <iostream>
#include <algorithm>
#include <bitset>
#include <complex>
#include <deque>
#include <exception>
#include <fstream>
#include <functional>
#include <iomanip>
#include <ios>
#include <iosfwd>
#include <iostream>
#include <istream>
#include <iterator>
#include <limits>
#include <list>
#include <locale>
#include <map>
#include <memory>
#include <new>
#include <numeric>
#include <ostream>
#include <queue>
#include <set>
#include <sstream>
#include <stack>
#include <stdexcept>
#include <streambuf>
#include <string>
#include <typeinfo>
#include <utility>
#include <valarray>
#include <vector>
#include <array>
#include <atomic>
#include <chrono>
#include <condition_variable>
#include <forward_list>
#include <future>
#include <initializer_list>
#include <mutex>
#include <random>
#include <ratio>
#include <regex>
#include <scoped_allocator>
#include <system_error>
#include <thread>
#include <tuple>
#include <typeindex>
#include <type_traits>
#include <unordered_map>
#include <unordered_set>
//#include <tchar.h>
//#include <intrin.h>

#define F first
#define S second
#define LL long long
#define MOD 1000000007
#define INF 1000000000
#define LINF 1000000000000000000

using namespace std;

const int N = 2e5 + 10;

LL a[N];
LL b[N];
bool p[N];
int indegree[N];
queue<int>que;
vector<int>ans;
vector<int>adj[N];

int main()
{
	/*freopen("haircut.in", "r", stdin);
	freopen("haircut.out", "w", stdout);*/

	int n;
	scanf("%d", &n);

	for (int i = 1;i <= n;i++)
		scanf("%lld", &a[i]);

	for (int i = 1;i <= n;i++)
		scanf("%lld", &b[i]);

	for (int i = 1;i <= n;i++)
		if (b[i] == -1)continue;
		else
		if (a[i] >= 0) {
			adj[i].push_back(b[i]);
			indegree[b[i]]++;
		}
		else {
			adj[b[i]].push_back(i);
			indegree[i]++;
		}

	for (int i = 1;i <= n;i++)
		if (!indegree[i])que.push(i);

	LL ans1 = 0;
	while (!que.empty()) {
		int t = que.front();
		que.pop();
		ans.push_back(t);

		p[t] = 1;
		ans1 += a[t];
		if (b[t] + 1)
		a[b[t]] += a[t];

		for (auto x : adj[t]) {
			indegree[x]--;
			if (!indegree[x] && a[x] >= 0)que.push(x);
		}
	}

	for (int i = 1;i <= n;i++)
		if (!p[i] && !indegree[i])que.push(i);

	while (!que.empty()) {
		int t = que.front();
		que.pop();
		ans.push_back(t);

		p[t] = 1;
		ans1 += a[t];
		if (b[t] + 1)
			a[b[t]] += a[t];

		for (auto x : adj[t]) {
			indegree[x]--;
			if (!indegree[x])que.push(x);
		}
	}

	for (int i = 1;i <= n;i++)
		if (!p[i])ans.push_back(i), ans1 += a[i];

	printf("%lld\n", ans1);
	for (auto x : ans)
		printf("%d ", x);

	cin >> n;
}


#include<iostream>
#include<cstdio>
#include<map>
#include<queue>
#include<vector>
#include<algorithm>

using namespace std;

#define ll long long

const int N = 2e5+5;

ll a[N]={0}, b[N]={0};

ll in[N]={0};

int main()
{
	int n;

	scanf("%lld",&n);

	for(int i=1;i<=n;++i)
	{
		scanf("%lld",&a[i]);
	}

	for(int i=1;i<=n;++i)
	{
		scanf("%lld",&b[i]);

		if(b[i]!=-1)
		{
			++in[b[i]];
		}
	}

	queue<ll> q;

	for(int i=1;i<=n;++i)
	{
		if(in[i]==0)//入度为0，不受其他点影响
		{
			q.push(i);
		}
	}

	vector<ll> good, bad;

	ll ans = 0;

	while(q.size()!=0)
	{
		ll u = q.front();

		q.pop();

		ans += a[u];

		if(a[u]>=0)//对后续点有好影响
		{
			good.push_back(u);

			if(b[u]==-1)
			{
				continue;
			}

			a[b[u]] += a[u];

			--in[b[u]];//已确认该结点的影响

			if(in[b[u]]==0)
			{
				q.push(b[u]);
			}
		}
		else
		{
			bad.push_back(u);

			if(b[u]==-1)
			{
				continue;
			}

			--in[b[u]];

			if(in[b[u]]==0)
			{
				q.push(b[u]);
			}
		}
	}

	printf("%d\n",ans);

	for(int i=0;i<good.size();++i)
	{
		printf("%d ",good[i]);
	}

	reverse(bad.begin(),bad.end());

	for(int i=0;i<bad.size();++i)
	{
		printf("%d ",bad[i]);
	}

	return 0;
}


#include<iostream>
#include<cstdio>
#include<map>
#include<queue>
#include<vector>
#include<algorithm>

using namespace std;

#define ll long long

const int N = 2e5+5;

ll a[N]={0}, b[N]={0};

ll in[N]={0};

int main()
{
	int n;

	scanf("%lld",&n);

	for(int i=1;i<=n;++i)
	{
		scanf("%lld",&a[i]);
	}

	for(int i=1;i<=n;++i)
	{
		scanf("%lld",&b[i]);

		if(b[i]!=-1)
		{
			++in[b[i]];
		}
	}

	queue<ll> q;

	for(int i=1;i<=n;++i)
	{
		if(in[i]==0)//入度为0，不受其他点影响
		{
			q.push(i);
		}
	}

	vector<ll> good, bad;

	ll ans = 0;

	while(q.size()!=0)
	{
		ll u = q.front();

		q.pop();

		ans += a[u];

		if(a[u]>=0)//对后续点有好影响
		{
			good.push_back(u);

			if(b[u]==-1)
			{
				continue;
			}

			a[b[u]] += a[u];

			--in[b[u]];//已确认该结点的影响

			if(in[b[u]]==0)
			{
				q.push(b[u]);
			}
		}
		else
		{
			bad.push_back(u);

			if(b[u]==-1)
			{
				continue;
			}

			--in[b[u]];

			if(in[b[u]]==0)
			{
				q.push(b[u]);
			}
		}
	}

	printf("%lld\n",ans);

	for(int i=0;i<good.size();++i)
	{
		printf("%lld ",good[i]);
	}

	reverse(bad.begin(),bad.end());

	for(int i=0;i<bad.size();++i)
	{
		printf("%lld ",bad[i]);
	}

	return 0;
}


#include<iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;

int p[200100],h[200100],f;
vector<int> v[200100];
long long int ans=0;
vector<int> lf,rt;

void dfs(int vr,int pr){
	int i=0,pp=0,hh=0;
	for(i=0;i<v[vr].size();i++){
		dfs(v[vr][i],vr);
	}

	if(p[vr]>0){
		lf.push_back(vr+1);
		ans+=p[vr];
		p[pr]+=p[vr];
	} else {
		ans+=p[vr];
		rt.push_back(vr+1);
	}
}

void solve(){
	int i,j,k,n,m,q,w;
	cin >> n;
	for (i=0;i<n;i++)cin >> p[i];
	for (i=0;i<n;i++)h[i]=0;
	for (i=0;i<n;i++)v[i].clear();
	for(i=0;i<n;i++){
		cin >> q;
		if(q!=-1){
			v[q-1].push_back(i);
			h[i]=1;
		}
	}

	for(i=0;i<n;i++)if(h[i]==0)
		dfs(i,i);
	cout << ans << endl;
	for(i=0;i<lf.size();i++)cout << lf[i] << " ";
	for(i=(int)rt.size()-1;i>=0;i--)cout << rt[i] << " ";
}

int main(){
#ifdef _DEBUG
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif
	int n,i,m,j,k;
	solve();
	return 0;
}


#include<iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;

int p[100100],h[100100],f;
vector<int> v[100100];
long long int ans=0;
vector<int> lf,rt;

void dfs(int vr,int pr){
	int i=0,pp=0,hh=0;
	for(i=0;i<v[vr].size();i++){
		dfs(v[vr][i],vr);
	}

	if(p[vr]>0){
		lf.push_back(vr+1);
		ans+=p[vr];
		p[pr]+=p[vr];
	} else {
		ans+=p[vr];
		rt.push_back(vr+1);
	}
}

void solve(){
	int i,j,k,n,m,q,w;
	cin >> n;
	for (i=0;i<n;i++)cin >> p[i];
	for (i=0;i<n;i++)h[i]=0;
	for (i=0;i<n;i++)v[i].clear();
	for(i=0;i<n;i++){
		cin >> q;
		if(q!=-1){
			v[q-1].push_back(i);
			h[i]=1;
		}
	}

	for(i=0;i<n;i++)if(h[i]==0)
		dfs(i,i);
	cout << ans << endl;
	for(i=0;i<lf.size();i++)cout << lf[i] << " ";
	for(i=(int)rt.size()-1;i>=0;i--)cout << rt[i] << " ";
}

int main(){
#ifdef _DEBUG
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif
	int n,i,m,j,k;
	solve();
	return 0;
}


#include<iostream>
#include<stdio.h>
#include<math.h>
#include<algorithm>
#include<string>
#include<vector>
using namespace std;

long long int p[200100],h[200100],f;
vector<int> v[200100];
long long int ans=0;
vector<int> lf,rt;

void dfs(int vr,int pr){
	int i=0,pp=0,hh=0;
	for(i=0;i<v[vr].size();i++){
		dfs(v[vr][i],vr);
	}

	if(p[vr]>0){
		lf.push_back(vr+1);
		ans+=p[vr];
		p[pr]+=p[vr];
	} else {
		ans+=p[vr];
		rt.push_back(vr+1);
	}
}

void solve(){
	int i,j,k,n,m,q,w;
	cin >> n;
	for (i=0;i<n;i++)cin >> p[i];
	for (i=0;i<n;i++)h[i]=0;
	for (i=0;i<n;i++)v[i].clear();
	for(i=0;i<n;i++){
		cin >> q;
		if(q!=-1){
			v[q-1].push_back(i);
			h[i]=1;
		}
	}

	for(i=0;i<n;i++)if(h[i]==0)
		dfs(i,i);
	cout << ans << endl;
	for(i=0;i<lf.size();i++)cout << lf[i] << " ";
	for(i=(int)rt.size()-1;i>=0;i--)cout << rt[i] << " ";
}

int main(){
#ifdef _DEBUG
	freopen("input.txt", "r", stdin);
	freopen("output.txt", "w", stdout);
#endif
	int n,i,m,j,k;
	solve();
	return 0;
}


#include <cstdio>
#include <cstring>
#include <iostream>
#include <vector>
using namespace std;

#define LL long long
#define M 200005
const LL INF = 1e15;

int n, b[M], root[M], cnt;
LL a[M], ans, f[M];
vector<int> G[M];

void dfs (int x, int fa){
    LL sum = 0;
    for (int i = 0; i < G[x].size(); i ++){
        int tmp = G[x][i];
        if (tmp != fa){
            dfs (tmp, x);
            sum += max (f[tmp], (LL)0);
        }
    }
    f[x] = sum + a[x];
}
void print (int x, int fa){
    for (int i = 0; i < G[x].size(); i ++){
        int tmp = G[x][i];
        if (tmp != fa){
            if (f[tmp] > 0)
                print (tmp, x);
        }
    }
    printf ("%d ", x);
    for (int i = 0; i < G[x].size(); i ++){
        int tmp = G[x][i];
        if (tmp != fa){
            if (f[tmp] <= 0)
                print (tmp, x);
        }
    }
}
int main (){
    scanf ("%d", &n);
    for (int i = 1; i <= n; i ++)
        scanf ("%lld", &a[i]);
    for (int i = 1; i <= n; i ++){
        scanf ("%d", &b[i]);
        if (b[i] != -1)
            G[b[i]].push_back (i);
        else
            root[++ cnt] = i;
    }
    for (int i = 1; i <= cnt; i ++){
        dfs (root[i], 0);
    }
    for (int i = 1; i <= n; i ++)
        ans += f[i];
    printf ("%lld\n", ans);
    for (int i = 1; i <= cnt; i ++){
        print (root[i], 0);
    }
    return 0;
}


#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <algorithm>
#include <cmath>
#include <complex>
#include <string>
using namespace std;

#define sz(a) ((int)a.size())

#define mp make_pair
#define pb push_back

#define frf(i, n) for(int i = 0; i < n; ++i)
#define frf1(i, n) for(int i = 1; i <= n; ++i)
#define frb(i, n) for(int i = (n-1); i >= 0; --i)
#define frb1(i, n) for(int i = n; i >= 1; --i)

typedef long long ll;
typedef long double ld;

typedef pair< int, int > pii;
typedef pair< ll, ll > pll;
typedef vector< int > vi;
typedef vector< ll > vll;
typedef vector< pii > vpii;
typedef vector< pll > vpll;

typedef complex < ld > cld;

int n;
ll a[210002];
ll b[210002];
vi g[210002];
bool mark[210002];

vi top;
vi tail;

ll answ;
vi res;

void dfs(int x) {
	frf(i, sz(g[x])) {
		int v = g[x][i];
		dfs(v);
	}
	top.pb(x);
}

void bra(int x) {
	if (mark[x]) res.pb(x);
	frf(i, sz(g[x])) {
		int v = g[x][i];
		bra(v);
	}
}

void solve() {
	scanf("%d", &n);
	frf1(i, n) {
		scanf("%lld", &a[i]);
		mark[i] = false;
	}

	frf1(i, n) {
		scanf("%lld", &b[i]);
		if (b[i] != -1) {
			g[b[i]].pb(i);
		}
	}

	frf1(i, n) {
		if (b[i] == -1) dfs(i);
	}

	frf(i, sz(top)) {
		int v = top[i];
		answ += a[v];
		if (a[v] < 0) {
			//cout << v << endl;
			//tail.pb(v);
			mark[v] = true;
		}
		else {
			res.pb(v);
			if (b[v] != -1) a[b[v]] += a[v];
		}
	}

	/*frf(i, sz(tail)) {
		res.pb(tail[i]);
	}*/
	frf1(i, n) {
		if (b[i] == -1) bra(i);
	}

	printf("%lld\n", answ);
	frf(i, sz(res)) {
		printf("%d ", res[i]);
	}
	printf("\n");

}

int main() {

    int t;
   	//cin>>t;
    t = 1;
    while(t) {
        --t;
        solve();
    }

    return 0;
}


#include <iostream>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <algorithm>
#include <cmath>
#include <complex>
#include <string>
using namespace std;

#define sz(a) ((int)a.size())

#define mp make_pair
#define pb push_back

#define frf(i, n) for(int i = 0; i < n; ++i)
#define frf1(i, n) for(int i = 1; i <= n; ++i)
#define frb(i, n) for(int i = (n-1); i >= 0; --i)
#define frb1(i, n) for(int i = n; i >= 1; --i)

typedef long long ll;
typedef long double ld;

typedef pair< int, int > pii;
typedef pair< ll, ll > pll;
typedef vector< int > vi;
typedef vector< ll > vll;
typedef vector< pii > vpii;
typedef vector< pll > vpll;

typedef complex < ld > cld;

int n;
ll a[210002];
ll b[210002];
vi g[210002];

vi top;
vi tail;

ll answ;
vi res;

void dfs(int x) {
	frf(i, sz(g[x])) {
		int v = g[x][i];
		dfs(v);
	}
	top.pb(x);
}

void solve() {
	scanf("%d", &n);
	frf1(i, n) {
		scanf("%lld", &a[i]);
	}

	frf1(i, n) {
		scanf("%lld", &b[i]);
		if (b[i] != -1) {
			g[b[i]].pb(i);
		}
	}

	frf1(i,n) {
		if (b[i] == -1) dfs(i);
	}

	frf(i, sz(top)) {
		int v = top[i];
		answ += a[v];
		if (a[v] < 0) tail.pb(v);
		else {
			res.pb(v);
			if (b[v] != -1) a[b[v]] += a[v];
		}
	}

	frf(i, sz(tail)) {
		res.pb(tail[i]);
	}

	printf("%lld\n", answ);
	frf(i, sz(res)) {
		printf("%d ", res[i]);
	}
	printf("\n");

}

int main() {

    int t;
   	//cin>>t;
    t = 1;
    while(t) {
        --t;
        solve();
    }

    return 0;
}


import sys
from collections import deque

readline = sys.stdin.buffer.readline

ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))

def solve():
    n = ni()
    a = nl()
    b = nl()
    ans = 0
    ent = [0]*n
    for x in b:
        if x >= 0:
            ent[x-1] += 1
    q = deque()
    G = [list() for _ in range(n)]
    for i in range(n):
        if not ent[i]:
            q.append(i)
    while q:
        v = q.popleft()
        ans += a[v]
        if b[v] < 0: continue
        x = b[v] - 1
        if a[v] >= 0:
            G[v].append(x)
            a[x] += a[v]
        else:
            G[x].append(v)
        ent[x] -= 1
        if not ent[x]: q.append(x)

    ent = [0]*n
    for l in G:
        for x in l:
            ent[x] += 1
    q = deque()
    for i in range(n):
        if not ent[i]:
            q.append(i)
    l = list()
    while q:
        v = q.popleft()
        l.append(v + 1)
        for x in G[v]:
            ent[x] -= 1
            if not ent[x]: q.append(x)
    print(ans)
    print(*l)
    return

solve()

# T = ni()
# for _ in range(T):
#     solve()


from collections import defaultdict
import sys
sys.setrecursionlimit(2 * 10**5)

n = int(input())
a = [0] + list(map(int, input().split()))
b = list(map(int, input().split()))

f = defaultdict(list)
num_list = [0] * (n + 1)
for index, nxt in enumerate(b):
    if nxt != -1:
        # print(index+1, nxt)
        f[index + 1].append(nxt)
        num_list[nxt] += 1
# print(num_list)
# print(f)
q = [i for i, v in enumerate(num_list) if i > 0 and v == 0]
res = 0
res_list = []
reverse_nege_list = []
while q:
    # res_list.extend(q)
    p = []
    for i in q:
        if a[i] > 0:
            res_list.append(i)
        else:
            reverse_nege_list.append(i)
        res += a[i]
        for nxt in f[i]:
            num_list[nxt] -= 1
            if num_list[nxt] == 0:
                p.append(nxt)
            if a[i] > 0:
                a[nxt] += a[i]
    q = p
print(res)
ans_list = res_list + reverse_nege_list[::-1]
print(" ".join(map(str, ans_list)))


from collections import defaultdict
import sys
sys.setrecursionlimit(2*10**5)

n = int(input())
a = [0] + list(map(int,input().split()))
b = list(map(int,input().split()))

f = defaultdict(list)
num_list = [0]*(n+1)
for index, nxt in enumerate(b):
    if nxt!=-1:
        # print(index+1, nxt)
        f[index+1].append(nxt)
        num_list[nxt] += 1
# print(num_list)
# print(f)
q = [i for i,v in enumerate(num_list) if i>0 and v==0]
res = 0
res_list = []
reverse_nege_list = []
while q:
    # res_list.extend(q)
    p = []
    for i in q:
        if a[i]>0:
            res_list.append(i)
        else:
            reverse_nege_list.append(i)
        res += a[i]
        for nxt in f[i]:
            num_list[nxt] -= 1
            if num_list[nxt]==0:
                p.append(nxt)
            if a[i]>0:
                a[nxt] += a[i]
    q = p
print(res)
print(res_list + reverse_nege_list[::-1])


from collections import Counter
n = int(input())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]

indeg = Counter(b)
s = []
for i in range(n):
    if i+1 not in indeg:
        s.append(i)
ans = 0
steps =[]
while s:
    index = s.pop()
    if a[index]>=0:
        steps.append(index+1)
        ans+=a[index]
    if b[index]!=-1:
        if a[index]>=0:
            a[b[index]-1]+=a[index]
        indeg[b[index]]-=1
        if indeg[b[index]] == 0:
            s.append(b[index]-1)
outdeg = {}
adj= {}
for i in range(n):
    if b[i]!=-1 and a[i]<0 and a[b[i]-1]<0:
        if b[i]-1 in adj:
            adj[b[i]-1].append(i)
        else:
            adj[b[i]-1] = [i]

s = []
for i in range(n):
    if a[i]<0:
        if b[i]!=-1 and a[b[i]-1]<0:
            outdeg[i] = 1
        else:
            s.append(i)

while s:
    index = s.pop()
    ans+=a[index]
    steps.append(index+1)
    if index in adj:
        for ele in adj[index]:
            outdeg[ele]-=1
            if outdeg[ele] == 0:
                s.append(ele)

print(ans)
for ele in steps:
    print(ele,end=' ')


from collections import Counter
n = int(input())
a = [int(i) for i in input().split()]
b = [int(i) for i in input().split()]

indeg = Counter(b)
s = []
for i in range(n):
    if i+1 not in indeg:
        s.append(i)
ans = 0
steps = []
while s:
    index = s.pop()
    if a[index]>=0:
        steps.append(index+1)
        ans+=a[index]
    if b[index]!=-1:
        if a[index]>=0:
            a[b[index]-1]+=a[index]
        indeg[b[index]]-=1
        if indeg[b[index]] == 0:
            s.append(b[index]-1)
#print(a)
for i in range(n):
    if a[i]<0:
        steps.append(i+1)
        ans+=a[i]

print(ans)
for ele in steps:
    print(ele,end=' ')


import sys
from collections import deque
input = sys.stdin.buffer.readline
def print(val):
    sys.stdout.write(val)
    sys.stdout.write('\n')
def prog():
    n = int(input())
    a = list(map(int,input().split()))
    b = list(map(int,input().split()))

    for i in range(n):
        b[i] -= 1
    radj = [[] for i in range(n)]
    adj  = [0]*n
    roots = []
    for i in range(n):
        if b[i] != -2:
            radj[b[i]].append(i)
            adj[i] = b[i]
        else:
            adj[i] = -2
            roots.append(i)

    s = deque(roots)
    neg_vals = []
    moves = []
    visited = [0]*n
    ans = 0
    while s:
        curr = s[-1]
        if not visited[curr]:
            for neighbor in radj[curr]:
                s.append(neighbor)
            visited[curr] = 1
        else:
            ans += a[curr]
            if a[curr] > 0:
                moves.append(s.pop())
                if adj[curr] != -2:
                    a[adj[curr]] += a[curr]
            else:
                neg_vals.append(s.pop())

    moves.extend(reversed(neg_vals))
    print(str(ans))
    print(" ".join(map(str,map(lambda x: x + 1, moves))))
prog()


from sys import *

#stdin = open('in.txt', 'r')

def main():

    n = int(stdin.readline().rstrip())
    a = [int(x) for x in stdin.readline().rstrip().split()]
    b = [int(x) for x in stdin.readline().rstrip().split()]

    countLink = dict()
    for i in b:
        countLink[i-1] = countLink.get(i - 1,0) + 1

    selected = []
    stack = []
    result = 0

    while len(selected) + len(stack) < n:

        hasAppend = False
        for i in range(n):
            if countLink.get(i,0) == 0:
                result += a[i]

                if a[i] > 0:
                    selected.append(i+1)
                    if b[i] != -1:
                        a[b[i] - 1] += a[i]
                else:
                    stack.append(i+1)

                countLink[b[i] - 1] = countLink.get(b[i] - 1,0) - 1
                countLink[i] = -1
                hasAppend = True
                break
        if not hasAppend:
            break

    print(result)

    for i in selected:
        print(i, end=' ')
    for i in reversed(stack):
        print(i, end= ' ')

main()


from sys import *

#stdin = open('in.txt', 'r')

def main():

    n = int(stdin.readline().rstrip())
    a = [int(x) for x in stdin.readline().rstrip().split()]
    b = [int(x) for x in stdin.readline().rstrip().split()]

    countLink = dict()
    for i in b:
        countLink[i-1] = countLink.get(i - 1,0) + 1

    preselect = []
    for i in range(n):
        if countLink.get(i, 0) == 0:
            preselect.append(i)

    selected = []
    stack = []
    result = 0

    while len(preselect) > 0:
        i = preselect.pop()
        if countLink.get(i,0) == 0:
            result += a[i]

            if a[i] > 0:
                selected.append(i+1)
                if b[i] != -1:
                    a[b[i] - 1] += a[i]
            else:
                stack.append(i+1)

            countLink[b[i] - 1] = countLink.get(b[i] - 1,0) - 1
            countLink[i] = -1
            if (countLink[b[i] - 1] == 0 and b[i] - 1 >= 0):
                preselect.append(b[i] - 1)

    print(result)

    for i in selected:
        print(i, end=' ')
    for i in reversed(stack):
        print(i, end= ' ')

main()


'''
@Author: nuoyanli
@Date: 2020-07-30 23:43:12
@LastEditTime: 2020-07-31 16:21:38
@Author's blog: https://blog.nuoyanli.com/
@Description: Don't forget the rich and the poor!
'''
import sys
from queue import Queue
readline = sys.stdin.readline
readlines = sys.stdin.readlines
Ns = lambda: readline().rstrip()
Ni = lambda: int(readline().rstrip())
Nm = lambda: map(int, readline().split())
Nl = lambda: list(map(int, readline().split()))
VPN = lambda x: print(*x, sep='\n')
q = Queue()
n = Ni()
z = Nl()
y = Nl()
z.insert(0, 0)
y.insert(0, 0)
deg = [0]*(max(y)*10)
for i in range(1, n+1):
    if y[i] != -1:
        deg[y[i]] += 1
for i in range(1, n+1):
    if deg[i] == 0:
        q.put(i)
Pns = 0
M1 = []
M2 = []
while not q.empty():
    x = q.get()
    if z[x] >= 0:
        M1.append(x)
        ans += z[x]
        if y[x] != -1:
            deg[y[x]] -= 1
            if deg[y[x]] == 0:
                q.put(y[x])
            z[y[x]] += z[x]
    else:
        M2.append(x)
        Pns += z[x]
        if y[x] != -1:
            deg[y[x]] -= 1
            if deg[y[x]] == 0:
                q.put(y[x])
print(Pns)
print(' '.join(map(str,  M1)), end=" ")
M2.reverse()
print(' '.join(map(str,  M2)))


'''
@Author: nuoyanli
@Date: 2020-07-30 23:43:12
@LastEditTime: 2020-07-31 16:21:38
@Author's blog: https://blog.nuoyanli.com/
@Description: Don't forget the rich and the poor!
'''
import sys
from queue import Queue
readline = sys.stdin.readline
readlines = sys.stdin.readlines
Zs = lambda: readline().rstrip()
Zi = lambda: int(readline().rstrip())
Zm = lambda: map(int, readline().split())
Zl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')
q = Queue()
n = Zi()
z = Zl()
y = Zl()
z.insert(0, 0)
y.insert(0, 0)
deg = [0]*(max(y)*10)
for i in range(1, n+1):
    if y[i] != -1:
        deg[y[i]] += 1
for i in range(1, n+1):
    if deg[i] == 0:
        q.put(i)
jana = 0
o9 = []
o10 = []
while not q.empty():
    x = q.get()
    if z[x] >= 0:
        o9.append(x)
        ans += z[x]
        if y[x] != -1:
            deg[y[x]] -= 1
            if deg[y[x]] == 0:
                q.put(y[x])
            z[y[x]] += z[x]
    else:
        o10.append(x)
        jana += z[x]
        if y[x] != -1:
            deg[y[x]] -= 1
            if deg[y[x]] == 0:
                q.put(y[x])
print(jana)
print(' '.join(map(str,  o9)), end=" ")
o10.reverse()
print(' '.join(map(str,  o10)))


'''
@Author: nuoyanli
@Date: 2020-07-30 23:43:12
@LastEditTime: 2020-07-31 16:21:38
@Author's blog: https://blog.nuoyanli.com/
@Description: Don't forget the rich and the poor!
'''
import sys
from queue import Queue
readline = sys.stdin.readline
readlines = sys.stdin.readlines
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')
q = Queue()
n = ni()
a = nl()
b = nl()
a.insert(0, 0)
b.insert(0, 0)
deg = [0]*(max(b)*10)
for i in range(1, n+1):
    if b[i] != -1:
        deg[b[i]] += 1
for i in range(1, n+1):
    if deg[i] == 0:
        q.put(i)
ans = 0
M1 = []
M2 = []
while not q.empty():
    x = q.get()
    if a[x] >= 0:
        M1.append(x)
        ans += a[x]
        if b[x] != -1:
            deg[b[x]] -= 1
            if deg[b[x]] == 0:
                q.put(b[x])
            a[b[x]] += a[x]
    else:
        M2.append(x)
        ans += a[x]
        if b[x] != -1:
            deg[b[x]] -= 1
            if deg[b[x]] == 0:
                q.put(b[x])
print(ans)
print(' '.join(map(str,  M1)), end=" ")
M2.reverse()
print(' '.join(map(str,  M2)))


import sys
from queue import Queue
readline = sys.stdin.readline
readlines = sys.stdin.readlines
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')
q = Queue()
n = ni()
a = nl()
b = nl()
a.insert(0, 0)
b.insert(0, 0)
deg = [0]*(max(b)*10)
for i in range(1, n+1):
    if b[i] != -1:
        deg[b[i]] += 1
for i in range(1, n+1):
    if deg[i] == 0:
        q.put(i)
PNS = 0
M1 = []
M2 = []
while not q.empty():
    x = q.get()
    if a[x] >= 0:
        M1.append(x)
        ans += a[x]
        if b[x] != -1:
            deg[b[x]] -= 1
            if deg[b[x]] == 0:
                q.put(b[x])
            a[b[x]] += a[x]
    else:
        M2.append(x)
        PNS += a[x]
        if b[x] != -1:
            deg[b[x]] -= 1
            if deg[b[x]] == 0:
                q.put(b[x])
print(PNS)
print(' '.join(map(str,  M1)), end=" ")
M2.reverse()
print(' '.join(map(str,  M2)))


import sys
from queue import Queue
readline = sys.stdin.readline
readlines = sys.stdin.readlines
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')
q = Queue()
n = ni()
z = nl()
b = nl()
z.insert(0, 0)
b.insert(0, 0)
deg = [0]*(max(b)*10)
for i in range(1, n+1):
    if b[i] != -1:
        deg[b[i]] += 1
for i in range(1, n+1):
    if deg[i] == 0:
        q.put(i)
PNS = 0
M1 = []
M2 = []
while not q.empty():
    x = q.get()
    if z[x] >= 0:
        M1.append(x)
        PNS += z[x]
        if b[x] != -1:
            deg[b[x]] -= 1
            if deg[b[x]] == 0:
                q.put(b[x])
            z[b[x]] += z[x]
    else:
        M2.append(x)
        PNS += z[x]
        if b[x] != -1:
            deg[b[x]] -= 1
            if deg[b[x]] == 0:
                q.put(b[x])
print(PNS)
print(' '.join(map(str,  M1)), end=" ")
M2.reverse()
print(' '.join(map(str,  M2)))


import sys
from queue import Queue
readline = sys.stdin.readline
readlines = sys.stdin.readlines
Us = lambda: readline().rstrip()
Ui = lambda: int(readline().rstrip())
Um = lambda: map(int, readline().split())
Ul = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')
q = Queue()
n = Ui()
z = Ul()
b = Ul()
z.insert(0, 0)
b.insert(0, 0)
deg = [0]*(max(b)*10)
for i in range(1, n+1):
    if b[i] != -1:
        deg[b[i]] += 1
for i in range(1, n+1):
    if deg[i] == 0:
        q.put(i)
PNS = 0
M1 = []
M2 = []
while not q.empty():
    x = q.get()
    if z[x] >= 0:
        M1.append(x)
        PNS += z[x]
        if b[x] != -1:
            deg[b[x]] -= 1
            if deg[b[x]] == 0:
                q.put(b[x])
            z[b[x]] += z[x]
    else:
        M2.append(x)
        PNS += z[x]
        if b[x] != -1:
            deg[b[x]] -= 1
            if deg[b[x]] == 0:
                q.put(b[x])
print(PNS)
print(' '.join(map(str,  M1)), end=" ")
M2.reverse()
print(' '.join(map(str,  M2)))


import sys
from queue import Queue
readline = sys.stdin.readline
readlines = sys.stdin.readlines
ns = lambda: readline().rstrip()
ni = lambda: int(readline().rstrip())
nm = lambda: map(int, readline().split())
nl = lambda: list(map(int, readline().split()))
prn = lambda x: print(*x, sep='\n')
q = Queue()
n = ni()
a = nl()
b = nl()
a.insert(0, 0)
b.insert(0, 0)
deg = [0]*(max(b)*10)
for i in range(1, n+1):
    if b[i] != -1:
        deg[b[i]] += 1
for i in range(1, n+1):
    if deg[i] == 0:
        q.put(i)
PNS = 0
M1 = []
M2 = []
while not q.empty():
    x = q.get()
    if a[x] >= 0:
        M1.append(x)
        PNS += a[x]
        if b[x] != -1:
            deg[b[x]] -= 1
            if deg[b[x]] == 0:
                q.put(b[x])
            a[b[x]] += a[x]
    else:
        M2.append(x)
        PNS += a[x]
        if b[x] != -1:
            deg[b[x]] -= 1
            if deg[b[x]] == 0:
                q.put(b[x])
print(PNS)
print(' '.join(map(str,  M1)), end=" ")
M2.reverse()
print(' '.join(map(str,  M2)))


import sys;input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**6)
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")

def getlist():
	return list(map(int, input().split()))

class Graph(object):
	def __init__(self):
		self.graph = defaultdict(list)

	def __len__(self):
		return len(self.graph)

	def add_edge(self, a, b):
		self.graph[a].append(b)

def DFS(G, W, P, Q, node):
	for i in G.graph[node]:
		DFS(G, W, P, Q, i)
		if W[i] >= 0:
			W[node] += W[i]
			P.append(i + 1)
		else:
			Q.append(i + 1)

#処理内容
def main():
	N = int(input())
	W = getlist()
	B = getlist()
	G = Graph()
	for i in range(N):
		u, v = B[i], i
		if u != -1:
			u -= 1
			G.add_edge(u, v)

	P = []
	Q = []
	for i in range(N):
		if B[i] == -1:
			DFS(G, W, P, Q, i)
			P.append(i + 1)

	P += Q[::-1]

	weight = sum(W)
	print(weight)
	print(*P)

if __name__ == '__main__':
	main()


import sys; input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")

def getlist():
	return list(map(int, input().split()))

class Graph(object):
	def __init__(self):
		self.graph = defaultdict(list)

	def __len__(self):
		return len(self.graph)

	def add_edge(self, a, b):
		self.graph[a].append(b)

P = []
Q = []

def DFS(G, W, A, visit, depth, node):
	for i in G.graph[node]:
		if visit[i] != 1:
			visit[i] = 1
			depth[i] = depth[node] + 1
			DFS(G, W, A, visit, depth, i)
			if W[i] > 0:
				W[node] += W[i]
				global P
				P.append(i + 1)
			else:
				global Q
				Q.append(i + 1)
	# if A[node] > 0:
	# 	global P
	# 	P.append(node + 1)

#処理内容
def main():
	N = int(input())
	A = getlist()
	B = getlist()
	G = Graph()
	W = [0] * N
	for i in range(N):
		W[i] = A[i]
		u, v = B[i], i
		if u != -1:
			u -= 1
			G.add_edge(u, v)

	visit = [0] * N
	depth = [INF] * N
	for i in range(N):
		if B[i] == -1:
			visit[i] = 1
			depth[i] = 0
			DFS(G, W, A, visit, depth, i)
			P.append(i + 1)

	M = len(Q)
	for i in range(M):
		P.append(Q[-1 - i])

	# for i in range(N):
	# 	if W[i] <= 0 and B[i] != -1:
	# 		P.append(i + 1)

	weight = sum(W)

	print(weight)
	print(*P)

if __name__ == '__main__':
	main()


import sys; input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")

def getlist():
	return list(map(int, input().split()))

class Graph(object):
	def __init__(self):
		self.graph = defaultdict(list)

	def __len__(self):
		return len(self.graph)

	def add_edge(self, a, b):
		self.graph[a].append(b)

def DFS(G, W, A, visit, depth, P, Q, node):
	for i in G.graph[node]:
		if visit[i] != 1:
			visit[i] = 1
			depth[i] = depth[node] + 1
			DFS(G, W, A, visit, depth, P, Q, i)
			if W[i] > 0:
				W[node] += W[i]
				P.append(i + 1)
			else:
				Q.append(i + 1)

#処理内容
def main():
	N = int(input())
	A = getlist()
	B = getlist()
	G = Graph()
	W = [0] * N
	for i in range(N):
		W[i] = A[i]
		u, v = B[i], i
		if u != -1:
			u -= 1
			G.add_edge(u, v)

	visit = [0] * N
	depth = [INF] * N
	P = []
	Q = []
	for i in range(N):
		if B[i] == -1:
			visit[i] = 1
			depth[i] = 0
			DFS(G, W, A, visit, depth, P, Q, i)
			P.append(i + 1)

	P += Q[::-1]
	# M = len(Q)
	# for i in range(M):
	# 	P.append(Q[-1 - i])

	weight = sum(W)
	print(weight)
	print(*P)

if __name__ == '__main__':
	main()


import sys; input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**8)
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")

def getlist():
	return list(map(int, input().split()))

class Graph(object):
	def __init__(self):
		self.graph = defaultdict(list)

	def __len__(self):
		return len(self.graph)

	def add_edge(self, a, b):
		self.graph[a].append(b)

def DFS(G, W, A, visit, depth, P, Q, node):
	for i in G.graph[node]:
		if visit[i] != 1:
			visit[i] = 1
			depth[i] = depth[node] + 1
			DFS(G, W, A, visit, depth, P, Q, i)
			if W[i] > 0:
				W[node] += W[i]
				P.append(i + 1)
			else:
				Q.append(i + 1)

#処理内容
def main():
	N = int(input())
	A = getlist()
	B = getlist()
	G = Graph()
	W = [0] * N
	for i in range(N):
		W[i] = A[i]
		u, v = B[i], i
		if u != -1:
			u -= 1
			G.add_edge(u, v)

	visit = [0] * N
	depth = [INF] * N
	P = []
	Q = []
	for i in range(N):
		if B[i] == -1:
			visit[i] = 1
			depth[i] = 0
			DFS(G, W, A, visit, depth, P, Q, i)
			P.append(i + 1)

	P += Q[::-1]
	# M = len(Q)
	# for i in range(M):
	# 	P.append(Q[-1 - i])

	weight = sum(W)
	print(weight)
	print(*P)

if __name__ == '__main__':
	main()


import sys; input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")

def getlist():
	return list(map(int, input().split()))

class Graph(object):
	def __init__(self):
		self.graph = defaultdict(list)

	def __len__(self):
		return len(self.graph)

	def add_edge(self, a, b):
		self.graph[a].append(b)

P = []

def DFS(G, W, A, visit, depth, node):
	for i in G.graph[node]:
		if visit[i] != 1:
			visit[i] = 1
			depth[i] = depth[node] + 1
			DFS(G, W, A, visit, depth, i)
			if W[i] > 0:
				W[node] += W[i]
				global P
				P.append(i + 1)
	# if A[node] > 0:
	# 	global P
	# 	P.append(node + 1)

#処理内容
def main():
	N = int(input())
	A = getlist()
	B = getlist()
	G = Graph()
	W = [0] * N
	for i in range(N):
		W[i] = A[i]
		u, v = B[i], i
		if u != -1:
			u -= 1
			G.add_edge(u, v)

	visit = [0] * N
	depth = [INF] * N
	for i in range(N):
		if B[i] == -1:
			visit[i] = 1
			depth[i] = 0
			DFS(G, W, A, visit, depth, i)
			P.append(i + 1)

	for i in range(N):
		if W[i] <= 0 and B[i] != -1:
			P.append(i + 1)

	weight = sum(W)

	print(weight)
	print(*P)

if __name__ == '__main__':
	main()


import sys;input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")

def getlist():
	return list(map(int, input().split()))

class Graph(object):
	def __init__(self):
		self.graph = defaultdict(list)

	def __len__(self):
		return len(self.graph)

	def add_edge(self, a, b):
		self.graph[a].append(b)

def DFS(G, W, P, Q, node):
	for i in G.graph[node]:
		DFS(G, W, P, Q, i)
		if W[i] > 0:
			W[node] += W[i]
			P.append(i + 1)
		else:
			Q.append(i + 1)

#処理内容
def main():
	N = int(input())
	W = getlist()
	B = getlist()
	G = Graph()
	for i in range(N):
		u, v = B[i], i
		if u != -1:
			u -= 1
			G.add_edge(u, v)

	P = []
	Q = []
	for i in range(N):
		if B[i] == -1:
			DFS(G, W, P, Q, i)
			P.append(i + 1)

	P += Q[::-1]

	weight = sum(W)
	print(weight)
	print(*P)

if __name__ == '__main__':
	import threading
	threading.stack_size(1024 * 100000)
	thread = threading.Thread(target=main)
	thread.start()
	thread.join()


import sys; input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")

def getlist():
	return list(map(int, input().split()))

class Graph(object):
	def __init__(self):
		self.graph = defaultdict(list)

	def __len__(self):
		return len(self.graph)

	def add_edge(self, a, b):
		self.graph[a].append(b)

P = []

def DFS(G, W, A, visit, depth, node):
	for i in G.graph[node]:
		if visit[i] != 1:
			visit[i] = 1
			depth[i] = depth[node] + 1
			DFS(G, W, A, visit, depth, i)
			if A[i] > 0:
				W[node] += W[i]
	if A[node] > 0:
		global P
		P.append(node + 1)

#処理内容
def main():
	N = int(input())
	A = getlist()
	B = getlist()
	G = Graph()
	W = [0] * N
	for i in range(N):
		W[i] = A[i]
		u, v = B[i], i
		if u != -1:
			u -= 1
			G.add_edge(u, v)

	visit = [0] * N
	depth = [INF] * N
	for i in range(N):
		if B[i] == -1:
			visit[i] = 1
			depth[i] = 0
			DFS(G, W, A, visit, depth, i)

	for i in range(N):
		if A[i] <= 0:
			P.append(i + 1)

	weight = sum(W)
	print(weight)
	print(*P)

if __name__ == '__main__':
	main()


import sys; input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")

def getlist():
	return list(map(int, input().split()))

class Graph(object):
	def __init__(self):
		self.graph = defaultdict(list)

	def __len__(self):
		return len(self.graph)

	def add_edge(self, a, b):
		self.graph[a].append(b)

P = []

def DFS(G, W, A, visit, depth, node):
	for i in G.graph[node]:
		if visit[i] != 1:
			visit[i] = 1
			depth[i] = depth[node] + 1
			DFS(G, W, A, visit, depth, i)
			if A[i] > 0:
				W[node] += W[i]
				global P
				P.append(i + 1)
	# if A[node] > 0:
	# 	global P
	# 	P.append(node + 1)

#処理内容
def main():
	N = int(input())
	A = getlist()
	B = getlist()
	G = Graph()
	W = [0] * N
	for i in range(N):
		W[i] = A[i]
		u, v = B[i], i
		if u != -1:
			u -= 1
			G.add_edge(u, v)

	visit = [0] * N
	depth = [INF] * N
	for i in range(N):
		if B[i] == -1:
			visit[i] = 1
			depth[i] = 0
			DFS(G, W, A, visit, depth, i)
			P.append(i + 1)

	for i in range(N):
		if A[i] <= 0 and B[i] != -1:
			P.append(i + 1)

	weight = sum(W)
	print(weight)
	print(*P)

if __name__ == '__main__':
	main()


import sys; input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")

def getlist():
	return list(map(int, input().split()))

class Graph(object):
	def __init__(self):
		self.graph = defaultdict(list)

	def __len__(self):
		return len(self.graph)

	def add_edge(self, a, b):
		self.graph[a].append(b)

P = []
Q = []

def DFS(G, W, A, visit, depth, node):
	for i in G.graph[node]:
		if visit[i] != 1:
			visit[i] = 1
			depth[i] = depth[node] + 1
			DFS(G, W, A, visit, depth, i)
			if W[i] > 0:
				W[node] += W[i]
				global P
				P.append(i + 1)
			else:
				Q.append(i + 1)
	# if A[node] > 0:
	# 	global P
	# 	P.append(node + 1)

#処理内容
def main():
	N = int(input())
	A = getlist()
	B = getlist()
	G = Graph()
	W = [0] * N
	for i in range(N):
		W[i] = A[i]
		u, v = B[i], i
		if u != -1:
			u -= 1
			G.add_edge(u, v)

	visit = [0] * N
	depth = [INF] * N
	for i in range(N):
		if B[i] == -1:
			visit[i] = 1
			depth[i] = 0
			DFS(G, W, A, visit, depth, i)
			P.append(i + 1)

	M = len(Q)
	for i in range(M):
		P.append(Q[-1 - i])

	# for i in range(N):
	# 	if W[i] <= 0 and B[i] != -1:
	# 		P.append(i + 1)

	weight = sum(W)

	print(weight)
	print(*P)

if __name__ == '__main__':
	main()


import sys;input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**9)
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")

def getlist():
	return list(map(int, input().split()))

class Graph(object):
	def __init__(self):
		self.graph = defaultdict(list)

	def __len__(self):
		return len(self.graph)

	def add_edge(self, a, b):
		self.graph[a].append(b)

def DFS(G, W, P, Q, node):
	for i in G.graph[node]:
		DFS(G, W, P, Q, i)
		if W[i] > 0:
			W[node] += W[i]
			P.append(i + 1)
		else:
			Q.append(i + 1)

#処理内容
def main():
	N = int(input())
	W = getlist()
	B = getlist()
	G = Graph()
	for i in range(N):
		u, v = B[i], i
		if u != -1:
			u -= 1
			G.add_edge(u, v)

	P = []
	Q = []
	for i in range(N):
		if B[i] == -1:
			DFS(G, W, P, Q, i)
			P.append(i + 1)

	P += Q[::-1]

	weight = sum(W)
	print(weight)
	print(*P)

if __name__ == '__main__':
	main()


import sys;input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")

def getlist():
	return list(map(int, input().split()))

class Graph(object):
	def __init__(self):
		self.graph = defaultdict(list)

	def __len__(self):
		return len(self.graph)

	def add_edge(self, a, b):
		self.graph[a].append(b)

def DFS(G, W, P, Q, node):
	for i in G.graph[node]:
		DFS(G, W, P, Q, i)
		if W[i] > 0:
			W[node] += W[i]
			P.append(i + 1)
		else:
			Q.append(i + 1)

#処理内容
def main():
	N = int(input())
	W = getlist()
	B = getlist()
	G = Graph()
	for i in range(N):
		u, v = B[i], i
		if u != -1:
			u -= 1
			G.add_edge(u, v)

	P = []
	Q = []
	for i in range(N):
		if B[i] == -1:
			DFS(G, W, P, Q, i)
			P.append(i + 1)

	P += Q[::-1]

	weight = sum(W)
	print(weight)
	print(*P)

if __name__ == '__main__':
	main()


import sys; input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**7)
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")

def getlist():
	return list(map(int, input().split()))

class Graph(object):
	def __init__(self):
		self.graph = defaultdict(list)

	def __len__(self):
		return len(self.graph)

	def add_edge(self, a, b):
		self.graph[a].append(b)

def DFS(G, W, A, visit, depth, P, Q, node):
	for i in G.graph[node]:
		if visit[i] != 1:
			visit[i] = 1
			depth[i] = depth[node] + 1
			DFS(G, W, A, visit, depth, P, Q, i)
			if W[i] > 0:
				W[node] += W[i]
				P.append(i + 1)
			else:
				Q.append(i + 1)
	# if A[node] > 0:
	# 	global P
	# 	P.append(node + 1)

#処理内容
def main():
	N = int(input())
	A = getlist()
	B = getlist()
	G = Graph()
	W = [0] * N
	for i in range(N):
		W[i] = A[i]
		u, v = B[i], i
		if u != -1:
			u -= 1
			G.add_edge(u, v)

	visit = [0] * N
	depth = [INF] * N
	P = []
	Q = []
	for i in range(N):
		if B[i] == -1:
			visit[i] = 1
			depth[i] = 0
			DFS(G, W, A, visit, depth, P, Q, i)
			P.append(i + 1)

	M = len(Q)
	for i in range(M):
		P.append(Q[-1 - i])

	# for i in range(N):
	# 	if W[i] <= 0 and B[i] != -1:
	# 		P.append(i + 1)

	weight = sum(W)

	print(weight)
	print(*P)

if __name__ == '__main__':
	main()


import sys;input = sys.stdin.buffer.readline
sys.setrecursionlimit(10**6)
from collections import defaultdict
con = 10 ** 9 + 7; INF = float("inf")

def getlist():
	return list(map(int, input().split()))

class Graph(object):
	def __init__(self):
		self.graph = defaultdict(list)

	def __len__(self):
		return len(self.graph)

	def add_edge(self, a, b):
		self.graph[a].append(b)

def DFS(G, W, P, Q, node):
	for i in G.graph[node]:
		DFS(G, W, P, Q, i)
		if W[i] > 0:
			W[node] += W[i]
			P.append(i + 1)
		else:
			Q.append(i + 1)

#処理内容
def main():
	N = int(input())
	W = getlist()
	B = getlist()
	G = Graph()
	for i in range(N):
		u, v = B[i], i
		if u != -1:
			u -= 1
			G.add_edge(u, v)

	visit = [0] * N
	depth = [INF] * N
	P = []
	Q = []
	for i in range(N):
		if B[i] == -1:
			DFS(G, W, P, Q, i)
			P.append(i + 1)

	P += Q[::-1]

	weight = sum(W)
	print(weight)
	print(*P)

if __name__ == '__main__':
	main()


#-----------------Take Input---------------------
n = int(input())
# a = [None] + [int(i) for i in input().split()]
# b = [None] + [int(i) for i in input().split()]

# a = [int(i) for i in input().split()]
# b = [int(i) for i in input().split()]
a = list(map(int, input().strip().split()))
b = list(map(int, input().strip().split()))

# print(n, a, b)
import sys
# print(sys.getrecursionlimit())
sys.setrecursionlimit(2000)

#--------------------------------------
# edge = {i: [] for i in range(n)}
# edge = dict()
edge = [[] for i in range(n)]
# edge
for i, x in enumerate(b):
    if x != -1:
        b[i] -= 1
        edge[b[i]].append(i)
        # edge[b[i]] = edge.get(b[i], [])+[i]

# print(edge, a, b)

used = [False]*n
order1, order2 = [], []
ans = 0

from collections import deque

def post_process(u):
    global ans, used, order1, order2, edge, a, b
    ans += a[u]
    if b[u] != -1 and a[u] > 0:
        a[b[u]] += a[u]

    if a[u] > 0: order1.append(u)
    else: order2.append(u)

# def dfs(u):
#     global ans, used, order1, order2, edge, a, b
#     stack = deque()
#     stack.append(u)
#     # post_process(u)

#     while stack:
#         u = stack.pop()
#         if used[u]: continue
#         # if not used[u]:
#         used[u] = True
#         # print(u)

#         for v in edge[u]:
#             if not used[v]:
#                 stack.append(v)
#                 # post_process(v)

#         post_process(u)

import sys

class RecursionLimit:
    def __init__(self, limit):
        self.limit = limit
        self.cur_limit = sys.getrecursionlimit()

    def __enter__(self):
        sys.setrecursionlimit(self.limit)

    def __exit__(self, exc_type, exc_value, exc_traceback):
        sys.setrecursionlimit(self.cur_limit)

def dfs(u):
    global ans, used, order1, order2, edge, a, b

    try: used[u] = True
    except: print("used error")
    # for v in edge.get(u, []):
    try: edges = edge[u]
    except: print("edges error")

    for v in edge[u]:
        if not used[v]:
            try: dfs(v)
            except: print("error inside")

    try:
        ans += a[u]
        if b[u] != -1 and a[u] > 0:
            a[b[u]] += a[u]
    except:
        print("posterror")

    if a[u] > 0: order1.append(u)
    else: order2.append(u)

for i in range(n):
    if not used[i]:
        try:
            MAX_LIMIT = 100000
            with RecursionLimit(MAX_LIMIT):
                dfs(i)
        except: print("dfs error")

print(ans)

# # import sys
# for i, o in enumerate(order1):
#     print(o+1, "",end="")
#     # if i % 1000 == 0: sys.stdout.flush()
# for i, o in enumerate(reversed(order2)):
#     print(o+1, "", end="")
#     # if i % 1000 == 0: sys.stdout.flush()
# print()

# print(edge)
print(" ".join(str(o+1) for o in order1), end=' ')
print(" ".join(str(o+1) for o in reversed(order2)))

''' generate
with open('in', 'w') as f:
    f.write(str(200000))
    f.write('\n')
    sign = 1
    for i in range(200_000):
        f.write(f'{-200000*sign} ')
    f.write('\n')
    for i in range(200_000):
        f.write(f'{i+1} ')

'''

'''
for /l %x in (1, 1, 3) do python cf_1388_d.py < input\cf_1388_d_%x
'''