#P8269. Bessie’s Moo Visits

    ID: 21448 Type: Default 1000ms 256MiB

Bessie’s Moo Visits

Bessie’s Moo Visits

Bessie has (N) cows (numbered (1,2,\ldots,N)) and each cow owns her own farm. For each (1 \le i \le N), cow (i) wishes to visit cow (a_i)'s farm, where (a_i \neq i). The visiting process is as follows for a given permutation (p = (p_1, p_2, \ldots, p_N)) of ({1,2,\ldots,N}):

For each (i = 1) to (N):

  • If cow \(a_{p_i}\) has already left her farm, then cow \(p_i\) stays at her own farm.
  • Otherwise, cow \(p_i\) leaves her farm to visit cow \(a_{p_i}\)'s farm, generating a happy moo count of \(v_{p_i}\) (with \(0 \le v_{p_i} \le 10^9\)).

By choosing the order (p) optimally, determine the maximum possible total moo count after all visits are processed.

A key observation is that if a cow (i)'s visit is successful then at the time of her visit, cow (a_i) must still be at her farm. This gives a dependency: if both cow (i) and cow (a_i) are to have successful visits then cow (i) must be processed before cow (a_i). In acyclic parts of the dependency graph, all cows can be included. However, each cycle must have at least one cow skipped in order to obtain a valid visitation order. It can be shown that the optimal total moo count is given by

[ \text{Answer} = \sum_{i=1}^{N} v_i - \sum_{\text{cycles}} (\min_{i \in \text{cycle}} v_i). ]

Your task is to implement a solution that reads (N), the array (a) and the array (v), and outputs the maximum total moo count possible.

inputFormat

The first line contains an integer \(N\) (\(2 \le N \le 10^5\)).

The second line contains \(N\) space-separated integers: \(a_1, a_2, \ldots, a_N\) where \(1 \le a_i \le N\) and \(a_i \neq i\) for each \(i\).

The third line contains \(N\) space-separated integers: \(v_1, v_2, \ldots, v_N\) (each satisfying \(0 \le v_i \le 10^9\)).

outputFormat

Output one integer, the maximum total moo count possible after processing the visits.

sample

2
2 1
5 100
100