E - 循環搬送網の回収口 解説 /

実行時間制限: 2 sec / メモリ制限: 1024 MiB

配点 : 433 点

問題文

N 個の搬送台があり、1 から N までの番号が付いています。搬送台 i からの送り先は搬送台 P_i に決まっています。自分自身が送り先でもかまいません。初め、搬送台 i には荷物が A_i 個あります。

高橋君は搬送台をちょうど 1 個選び、回収口にします。回収口にある荷物は、その場ですべて回収されます。その後、各荷物は現在いる搬送台から送り先へ移動することを繰り返し、回収口に初めて着いた時点で回収されます。回収された荷物は、それ以降移動しません。荷物どうしは互いの移動に影響しません。

回収される荷物それぞれについて、回収までに移動した回数を数え、その総和を得点とします。初めから回収口にある荷物の移動回数は 0 です。回収口に一度も着かない荷物は、得点に含めません。

回収口を適切に選んだときの、得点の最大値を求めてください。

制約

  • 1 \leq N \leq 200000
  • 1 \leq P_i \leq N (1 \leq i \leq N)
  • 1 \leq A_i \leq 1000000 (1 \leq i \leq N)
  • 入力はすべて整数である。

入力

入力は以下の形式で標準入力から与えられる。

N
P_1 P_2 \ldots P_N
A_1 A_2 \ldots A_N
  • 1 行目には搬送台の個数 N が与えられる。
  • 2 行目には各搬送台の送り先 P_1,P_2,\ldots,P_N が与えられる。
  • 3 行目には初めの荷物の個数 A_1,A_2,\ldots,A_N が与えられる。

出力

得点の最大値を整数で出力せよ。


入力例 1

3
2 3 1
1 2 3

出力例 1

7

入力例 2

3
1 2 3
5 2 9

出力例 2

0

入力例 3

6
2 3 1 2 4 3
1 2 4 3 2 5

出力例 3

35

入力例 4

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

出力例 4

69

入力例 5

1
1
1000000

出力例 5

0

Score : 433 pts

Problem Statement

There are N conveyor platforms, numbered 1 to N. The destination from conveyor platform i is fixed to conveyor platform P_i. The destination may be the platform itself. Initially, conveyor platform i has A_i packages.

Takahashi will choose exactly one conveyor platform to be the collection port. All packages at the collection port are immediately collected on the spot. After that, each package repeatedly moves from its current platform to its destination platform, and is collected the first time it reaches the collection port. Once collected, a package does not move anymore. Packages do not affect each other's movements.

For each collected package, we count the number of moves it made until it was collected, and the sum of these counts is the score. The number of moves for a package initially at the collection port is 0. Packages that never reach the collection port are not included in the score.

Find the maximum possible score when the collection port is chosen optimally.

Constraints

  • 1 \leq N \leq 200000
  • 1 \leq P_i \leq N (1 \leq i \leq N)
  • 1 \leq A_i \leq 1000000 (1 \leq i \leq N)
  • All input values are integers.

Input

The input is given from Standard Input in the following format:

N
P_1 P_2 \ldots P_N
A_1 A_2 \ldots A_N
  • The first line contains the number of conveyor platforms, N.
  • The second line contains the destination of each conveyor platform, P_1,P_2,\ldots,P_N.
  • The third line contains the initial number of packages, A_1,A_2,\ldots,A_N.

Output

Print the maximum possible score as an integer.


Sample Input 1

3
2 3 1
1 2 3

Sample Output 1

7

Sample Input 2

3
1 2 3
5 2 9

Sample Output 2

0

Sample Input 3

6
2 3 1 2 4 3
1 2 4 3 2 5

Sample Output 3

35

Sample Input 4

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

Sample Output 4

69

Sample Input 5

1
1
1000000

Sample Output 5

0