CF1027D.Mouse Hunt

传统题 时间 2000 ms 内存 256 MiB 9 尝试 27 已通过 9 标签

Mouse Hunt

Medicine faculty of Berland State University has just finished their admission campaign. As usual, about 80%80\% of applicants are girls and majority of them are going to live in the university dormitory for the next 44 (hopefully) years.

The dormitory consists of nn rooms and a single mouse! Girls decided to set mouse traps in some rooms to get rid of the horrible monster. Setting a trap in room number ii costs cic_i burles. Rooms are numbered from 11 to nn.

Mouse doesn't sit in place all the time, it constantly runs. If it is in room ii in second tt then it will run to room aia_i in second t+1t + 1 without visiting any other rooms inbetween (i=aii = a_i means that mouse won't leave room ii). It's second 00 in the start. If the mouse is in some room with a mouse trap in it, then the mouse get caught into this trap.

That would have been so easy if the girls actually knew where the mouse at. Unfortunately, that's not the case, mouse can be in any room from 11 to nn at second 00.

What it the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from?

Input

The first line contains as single integers nn (1n21051 \le n \le 2 \cdot 10^5) — the number of rooms in the dormitory.

The second line contains nn integers c1,c2,,cnc_1, c_2, \dots, c_n (1ci1041 \le c_i \le 10^4) — cic_i is the cost of setting the trap in room number ii.

The third line contains nn integers a1,a2,,ana_1, a_2, \dots, a_n (1ain1 \le a_i \le n) — aia_i is the room the mouse will run to the next second after being in room ii.

Output

Print a single integer — the minimal total amount of burles girls can spend to set the traps in order to guarantee that the mouse will eventually be caught no matter the room it started from.

Note

In the first example it is enough to set mouse trap in rooms 11 and 44. If mouse starts in room 11 then it gets caught immideately. If mouse starts in any other room then it eventually comes to room 44.

In the second example it is enough to set mouse trap in room 22. If mouse starts in room 22 then it gets caught immideately. If mouse starts in any other room then it runs to room 22 in second 11.

Here are the paths of the mouse from different starts from the third example:

  • 1221 \rightarrow 2 \rightarrow 2 \rightarrow \dots;
  • 222 \rightarrow 2 \rightarrow \dots;
  • 3223 \rightarrow 2 \rightarrow 2 \rightarrow \dots;
  • $4 \rightarrow 3 \rightarrow 2 \rightarrow 2 \rightarrow \dots$;
  • $5 \rightarrow 6 \rightarrow 7 \rightarrow 6 \rightarrow \dots$;
  • 6766 \rightarrow 7 \rightarrow 6 \rightarrow \dots;
  • 7677 \rightarrow 6 \rightarrow 7 \rightarrow \dots;

So it's enough to set traps in rooms 22 and 66.

Samples

5
1 2 3 2 10
1 3 4 3 3
3
4
1 10 2 10
2 4 2 2
10
7
1 1 1 1 1 1 1
2 2 2 3 6 7 6
2

在线编程 IDE

建议全屏模式获得最佳体验