#d1905. Mouse Hunt

Mouse Hunt

Mouse Hunt

Problem Description

There are nn rooms numbered from 11. A mouse will appear in some room.

When the mouse is in room ii (1≤i≤n1 \le i \le n) at a given moment, it will arrive at room pip_i in the next moment (if i=pii = p_i, the mouse never leaves room ii).

The cost of placing a mousetrap in room ii is wiw_i. Find the minimum total cost such that, no matter which room the mouse appears in, it will eventually arrive at a room that has a mousetrap.

Input Format

The first line contains an integer nn (1≤n≤2000001 \le n \le 200000).

The second line contains nn integers wiw_i (1≤wi≤100001 \le w_i \le 10000), the cost of placing a mousetrap in room ii.

The third line contains nn integers pip_i (1≤pi≤n1 \le p_i \le n), the room the mouse will go to from room ii.

Output Format

Output one integer: the minimum cost satisfying the condition.

Sample Input 1

5
1 2 3 2 10
1 3 4 3 3

Sample Output 1

3

Sample Input 2

4
1 10 2 10
2 4 2 2

Sample Output 2

10

Sample Input 3

7
1 1 1 1 1 1 1
2 2 2 3 6 7 6

Sample Input 4

2

Sample Explanation

In the first sample, you can place mousetraps in rooms 1 and 4. If the mouse appears in room 1, it is caught by the trap in room 1; otherwise it is caught by the trap in room 4.

In the second sample, you can place a mousetrap in room 2; no matter which room the mouse appears in, it will be caught by the trap in room 2.

These are the possible trajectories of the mouse in the third sample:

1→2→2→…;
2→2→…;
3→2→2→…;
4→3→2→2→…;
5→6→7→6→…;
6→7→6→…;
7→6→7→…;

So you can place mousetraps in rooms 2 and 6.