#P4437. Maximum Weighted Legal Permutation
Maximum Weighted Legal Permutation
Maximum Weighted Legal Permutation
You are given two arrays of length n: an array a with elements \(a_1,a_2,\dots,a_n\) (with \(0 \le a_i \le n\)) and an array w with elements \(w_1,w_2,\dots,w_n\). We call a permutation \(p=(p_1,p_2,\dots,p_n)\) of \(\{1,2,\dots,n\}\) a legal permutation if and only if it satisfies the condition:
For every pair of indices \(j\) and \(k\) with \(1 \le j \le k \le n\), we have \[ a_{p_j} \neq p_k. \]
An equivalent way to express this is: for every index \(i\) with \(a_i \neq 0\), if \(a_i = x\) then in the permutation the number \(x\) must appear before \(i\). (In particular, note that if \(a_i=i\) the condition fails immediately.)
For a legal permutation \(p\), its weight is defined as
[ W(p)=w_{p_1}+2w_{p_2}+\cdots+nw_{p_n}. ]
Your task is to find the maximum weight among all legal permutations. If no legal permutation exists, output \(-1\).
Note: Some test cases may illustrate examples of legal and illegal permutations.
inputFormat
The first line contains a single integer \(n\) (the number of elements).
The second line contains \(n\) integers \(a_1,a_2,\dots,a_n\), separated by spaces.
The third line contains \(n\) integers \(w_1,w_2,\dots,w_n\), separated by spaces.
Note: Indices are considered from \(1\) to \(n\).
outputFormat
Output a single integer: the maximum weight of any legal permutation, or \(-1\) if no legal permutation exists.
sample
3
0 1 1
1 2 3
14