#P11842. Idempotent Function Transformation

    ID: 13943 Type: Default 1000ms 256MiB

Idempotent Function Transformation

Idempotent Function Transformation

Bessie has a special function \( f(x) \) defined on integers from \(1\) to \(N\) by \( f(x) = a_x \), where each \( a_i \) is an integer in \([1, N]\). Bessie wants the function to be idempotent, meaning that for all \( x \in [1, N] \), we have \( f(f(x)) = f(x) \).

You are allowed to change the value \( a_i \) to any integer in \([1, N]\) at a cost of \( c_i \). Determine the minimum total cost required so that the resulting function \( f(x) \) becomes idempotent.

Note: A function \( f \) is idempotent if every value in its image is a fixed point, i.e., if \( y = f(x) \) then \( f(y) = y \).

inputFormat

The first line contains a single integer \( N \) (\(1 \leq N \leq 2 \cdot 10^5\)).

The second line contains \( N \) integers: \( a_1, a_2, \ldots, a_N \) (each between \(1\) and \(N\)), which define \( f(x) = a_x \).

The third line contains \( N \) integers: \( c_1, c_2, \ldots, c_N \) (each between \(1\) and \(10^9\)), where \( c_i \) is the cost to change \( a_i \) to any number in \([1, N]\).

outputFormat

Output a single integer, the minimum total cost required to modify the function so that \( f(f(x)) = f(x) \) for every \( x \in [1, N] \).

sample

1
1
5
0