P27289 [AtCoder] Two Step Sort
省选
题目描述

Problem Description

There are $ N $ boxes and $ N $ balls, each numbered from $ 1 $ to $ N $. Each box can contain exactly one ball, and initially, box $ i $ contains ball $ P_i $. All boxes are initially closed.

There will be two move events, each following these steps:

  1. Open some boxes. Opening a box incurs a fixed cost.
  2. Move balls freely between the opened boxes, ensuring that each box contains exactly one ball at the end.
  3. Close all opened boxes.

The cost to open box $ i $ is $ A_i $ during the first event and $ B_i $ during the second event. After the two move events, each box $ i $ must contain ball $ i $. Find the minimum total cost required to achieve this.

Input Format

The input is given from the standard input in the following format:

$ N $ $ P_1 $ $ P_2 $ $\ldots$ $ P_N $ $ A_1 $ $ A_2 $ $\ldots$ $ A_N $ $ B_1 $ $ B_2 $ $\ldots$ $ B_N $

Output Format

Output the minimum total cost in one line.

Sample Input and Output

Sample Input #1

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

Sample Output #1

28

Sample Input #2

1
1
1000000000
1000000000

Sample Output #2

0

Notes/Hints

Constraints

  • $1 \leq N \leq 10^5$
  • $1 \leq P_i \leq N$
  • $P_i \neq P_j$ for $i \neq j$
  • $1 \leq A_i \leq 10^9$
  • $1 \leq B_i \leq 10^9$
  • All inputs are integers.

Sample Explanation 1

During the first move event, open boxes $ 2 $ and $ 4 $, moving ball $ 1 $ to box $ 2 $ and ball $ 4 $ to box $ 4 $. This incurs a cost of $ 8 $. During the second move event, open boxes $ 1 $, $ 2 $, $ 3 $, and $ 5 $, moving balls $ 1 $, $ 2 $, $ 3 $, and $ 5 $ to their respective target boxes. This incurs a cost of $ 20 $. The total cost of $ 28 $ is the minimum required to achieve the condition.

Sample Explanation 2

The condition might already be satisfied.

输入格式

见题面 Input 部分

输出格式

见题面 Output 部分

样例输入
5 2 4 5 1 3 11 5 3 3 8 4 6 7 9 3
样例输出
28