#P11842. [USACO25FEB] Bessie's Function G

[USACO25FEB] Bessie's Function G

Description

Bessie has a special function f(x)f(x) that takes as input an integer in [1,N][1, N] and returns an integer in [1,N][1, N] (1N21051 \le N \le 2 \cdot 10^5). Her function f(x)f(x) is defined by NN integers a1aNa_1 \ldots a_N where f(x)=axf(x) = a_x (1aiN1 \le a_i \le N).

Bessie wants this function to be idempotent. In other words, it should satisfy f(f(x))=f(x)f(f(x)) = f(x) for all integers x[1,N]x \in [1, N].

For a cost of cic_i, Bessie can change the value of aia_i to any integer in [1,N][1, N] (1ci1091 \le c_i \le 10^9). Determine the minimum total cost Bessie needs to make f(x)f(x) idempotent.

Input Format

The first line contains NN.

The second line contains NN space-separated integers a1,a2,,aNa_1,a_2,\dots,a_N.

The third line contains NN space-separated integers c1,c2,,cNc_1,c_2,\dots,c_N.

Output Format

Output the minimum total cost Bessie needs to make f(x)f(x) idempotent.

5
2 4 4 5 3
1 1 1 1 1
3
8
1 2 5 5 3 3 4 4
9 9 2 5 9 9 9 9
7

Hint

For Sample 1:

We can change a1=4a_1 = 4, a4=4a_4 = 4, a5=4a_5 = 4. Since all cic_i equal one, the total cost is equal to 33, the number of changes. It can be shown that there is no solution with only 22 or fewer changes.

For Sample 2:

We change a3=3a_3 = 3 and a4=4a_4 = 4. The total cost is 2+5=72+5=7.

SCORING:

Subtasks:

  • Input 3: N20N\le 20
  • Inputs 4-9: aiia_i\ge i
  • Inputs 10-15: All aia_i are distinct.
  • Inputs 16-21: No additional constraints.

Additionally, in each of the last three subtasks, the first half of tests will satisfy ci=1c_i=1 for all ii.