Bessie's Function

시간 제한2초메모리 제한2048 MB

요약
원소마다 변경 비용이 주어진 함수에서 f(f(x)) = f(x)가 모든 x에 대해 성립하도록 최소 비용으로 값을 바꾸는 문제입니다.
난이도

어려움10점 중 8점

유형
그래프, 그리디, 유니온 파인드, 동적 계획법
정답자
아직 제출이 없습니다

문제

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] (1≤N≤2⋅1051 \le N \le 2 \cdot 10^5). Her function f(x)f(x) is defined by NN integers a_1…a_Na\_1 \ldots a\_N where f(x)=a_xf(x) = a\_x (1≤a_i≤N1 \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 c_ic\_i, Bessie can change the value of a_ia\_i to any integer in \[1,N]\[1, N] (1≤c_i≤1091 \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 a_1,a_2,…,a_Na\_1,a\_2,\dots,a\_N.

The third line contains NN space-separated integers c_1,c_2,…,c_Nc\_1,c\_2,\dots,c\_N.

출력

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

예제2

  1. 예제 1

    입력
    5
    2 4 4 5 3
    1 1 1 1 1
    
    예상 출력
    3
    
  2. 예제 2

    입력
    8
    1 2 5 5 3 3 4 4
    9 9 2 5 9 9 9 9
    
    예상 출력
    7