1. 程式人生 > 實用技巧 >CodeForces 1388D Captain Flint and Treasure

CodeForces 1388D Captain Flint and Treasure

Captain Fint is involved in another treasure hunt, but have found only one strange problem. The problem may be connected to the treasure's location or may not. That's why captain Flint decided to leave the solving the problem to his crew and offered an absurdly high reward: one day off. The problem itself sounds like this...

There are two arraysaaandbbof lengthnn. Initially, anansansis equal to00and the following operation is defined:

  1. Choose positionii(1in1≤i≤n);
  2. Addaiaitoansans;
  3. Ifbi1bi≠−1then addaiaitoabiabi.

What is the maximumansansyou can get by performing the operation on eachii(

1in1≤i≤n)exactly once?

Uncle Bogdan is eager to get the reward, so he is asking your help to find the optimal order of positions to perform the operation on them.

Input

The first line contains the integernn(1n21051≤n≤2⋅105)— the length of arraysaaandbb.

The second line contains

nnintegersa1,a2,,ana1,a2,…,an(106ai106−106≤ai≤106).

The third line containsnnintegersb1,b2,,bnb1,b2,…,bn(1bin1≤bi≤norbi=1bi=−1).

Additional constraint: it's guaranteed that for anyii(1in1≤i≤n) the sequencebi,bbi,bbbi,bi,bbi,bbbi,…is not cyclic, in other words it will always end with1−1.

Output

In the first line, print the maximumansansyou can get.

In the second line, print the order of operations:nndifferent integersp1,p2,,pnp1,p2,…,pn(1pin1≤pi≤n). Thepipiis the position which should be chosen at theii-th step. If there are multiple orders, print any of them.

Examples

Input
3
1 2 3
2 3 -1
Output
10
1 2 3 
Input
2
-1 100
2 -1
Output
99
2 1 
Input
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output
-9
3 5 6 1 9 4 10 7 8 2

拓撲排序b,然後判斷每一個a的值小於0就加入末尾,大於0就加入開頭

#define _CRT_SECURE_NO_WARNINGS
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cstdlib>
#include<cmath>
#include<map>
#include<queue>
using namespace std;
typedef long long ll;
#define Inf 0x3f3f3f3f
#define Maxn 20

const int N = 2e5 + 10;

int n, m, cnt = 1;
int du[N], b[N], p[N];
ll a[N];
queue<int> Q;
ll ans = 0;

int main() {
    scanf("%d", &n);
    for (int i = 1; i <= n; ++i) scanf("%I64d", &a[i]);
    for (int i = 1; i <= n; ++i) {
        scanf("%d", &b[i]);
        if (b[i] != -1)du[b[i]]++;
    }
    for (int i = 1; i <= n; ++i) if (!du[i]) Q.push(i);
    int l = 1, r = n, x;
    while (!Q.empty()) {
        x = Q.front(); Q.pop();
        ans += a[x];
        if (a[x] < 0) {
            p[r] = x; --r;
            if (b[x] != -1) {
                --du[b[x]];
                if (!du[b[x]]) Q.push(b[x]);
            }
        }
        else {
            p[l] = x; ++l;
            if (b[x] != -1) {
                a[b[x]] += a[x];
                --du[b[x]];
                if (!du[b[x]]) Q.push(b[x]);
            }
        }
    }
    printf("%I64d\n", ans);
    for (int i = 1; i <= n; ++i) printf("%d ", p[i]); puts("");
    return 0;

    
}