PivotOJ

Bessie's Function

시간 제한: 2000ms메모리 제한: 2048MB출처: USACO 2025 February GoldBOJ 33729

문제

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.

입력

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 the minimum total cost Bessie needs to make f(x)f(x) idempotent.

예제

예제 1

입력
5
2 4 4 5 3
1 1 1 1 1
출력
3

예제 2

입력
8
1 2 5 5 3 3 4 4
9 9 2 5 9 9 9 9
출력
7
코드를 제출하려면 로그인하세요.