Codeforces Round 660 (Div. 2)
D
Captain Flint and Treasure
Codeforces
2000
原题
← CE →
翻译中…

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 arrays $a$ and $b$ of length $n$. Initially, an $ans$ is equal to $0$ and the following operation is defined:

翻译中…
  1. Choose position $i$ ($1 \le i \le n$);
  2. Add $a_i$ to $ans$;
  3. If $b_i \neq -1$ then add $a_i$ to $a_{b_i}$.
翻译中…

What is the maximum $ans$ you can get by performing the operation on each $i$ ($1 \le i \le 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 integer $n$ ($1 \le n \le 2 \cdot 10^5$) — the length of arrays $a$ and $b$.

翻译中…

The second line contains $n$ integers $a_1, a_2, \ldots, a_n$ ($−10^6 \le a_i \le 10^6$).

翻译中…

The third line contains $n$ integers $b_1, b_2, \ldots, b_n$ ($1 \le b_i \le n$ or $b_i = -1$).

翻译中…

Additional constraint: it's guaranteed that for any $i$ ($1 \le i \le n$) the sequence $b_i, b_{b_i}, b_{b_{b_i}}, \ldots$ is not cyclic, in other words it will always end with $-1$.

翻译中…

Output

翻译中…

In the first line, print the maximum $ans$ you can get.

翻译中…

In the second line, print the order of operations: $n$ different integers $p_1, p_2, \ldots, p_n$ ($1 \le p_i \le n$). The $p_i$ is the position which should be chosen at the $i$-th step. If there are multiple orders, print any of them.

翻译中…

样例

Input #1
3
1 2 3
2 3 -1
Output #1
10
1 2 3
InputCopy OutputCopy
Input #2
2
-1 100
2 -1
Output #2
99
2 1
InputCopy OutputCopy
Input #3
10
-10 -1 2 2 5 -2 -3 -4 2 -6
-1 -1 2 2 -1 5 5 7 7 9
Output #3
-9
3 5 6 1 9 4 10 7 8 2
InputCopy OutputCopy
题目信息
题号
1388D
时间限制
2 s
内存限制
256 MB
标签
数据结构
DFS 及类似
图论
贪心
模拟
树

题面与样例版权归 Codeforces 及出题人所有;中文翻译由 AI 生成(CI 管线),如有出入请以原文为准。