atcoder#ABC256E. [ABC256E] Takahashi's Anguish

[ABC256E] Takahashi's Anguish

Score : 500500 points

Problem Statement

There are NN people numbered 11 through NN. Takahashi has decided to choose a sequence P=(P1,P2,,PN)P = (P_1, P_2, \dots, P_N) that is a permutation of integers from 11 through NN, and give a candy to Person P1P_1, Person P2P_2, \dots, and Person PNP_N, in this order. Since Person ii dislikes Person XiX_i, if Takahashi gives a candy to Person XiX_i prior to Person ii, then Person ii gains frustration of CiC_i; otherwise, Person ii's frustration is 00. Takahashi may arbitrarily choose PP. What is the minimum possible sum of their frustration?

Constraints

  • 2N2×1052 \leq N \leq 2 \times 10^5
  • 1XiN1 \leq X_i \leq N
  • XiiX_i \neq i
  • 1Ci1091 \leq C_i \leq 10^9
  • All values in input are integers.

Input

Input is given from Standard Input in the following format:

NN

X1X_1 X2X_2 \dots XNX_N

C1C_1 C2C_2 \dots CNC_N

Output

Print the answer.

3
2 3 2
1 10 100
10

If he lets P=(1,3,2)P = (1, 3, 2), only Person 22 gains a positive amount of frustration, in which case the sum of their frustration is 1010. Since it is impossible to make the sum of frustration smaller, the answer is 1010.

8
7 3 5 5 8 4 1 2
36 49 73 38 30 85 27 45
57