Description
Given n integers a1,a2,…,an,0≤ai≤n, and n integers w1,w2,…,wn. Call a permutation ap1,ap2,…,apn of a1,a2,…,an a valid permutation of a1,a2,…,an if and only if it satisfies: for any k and any j, if j≤k, then apj=pk. (In other words: for any k and any j, if pk=apj, then k<j.) Define the weight of this valid permutation as wp1+2wp2+⋯+nwpn.
You need to find the maximum weight among all valid permutations. If no valid permutation exists, output −1.
The sample explanations include examples of valid and invalid permutations.
The first line contains an integer n.
The next line contains n integers, denoting a1,a2,…,an. The following line contains n integers, denoting w1,w2,…,wn.
Output a single integer representing the answer.
3
0 1 1
5 7 3
32
3
2 3 1
1 2 3
-1
10
6 6 10 1 7 0 0 1 7 7
16 3 10 20 5 14 17 17 16 13
809
Hint
Sample Explanation 1
For a1=0,a2=1,a3=1, its permutations are:
- a1=0,a2=1,a3=1, this is a valid permutation, and its weight is 1×5+2×7+3×3=28;
- a2=1,a1=0,a3=1, this is an invalid permutation because ap2 equals p2;
- a1=0,a3=1,a2=1, this is a valid permutation, and its weight is 1×5+2×3+3×7=32;
- a3=1,a1=0,a2=1, this is an invalid permutation because ap1 equals p2;
- a2=1,a3=1,a1=0, this is an invalid permutation because ap1 equals p3;
- a3=1,a2=1,a1=0, this is an invalid permutation because ap1 equals p3.
Therefore, the maximum weight is 32.
Sample Explanation 2
For a1=2,a2=3,a3=1, its permutations are:
- a1=2,a2=3,a3=1, this is an invalid permutation because ap1 equals p2;
- a2=3,a1=2,a3=1, this is an invalid permutation because ap1 equals p3;
- a1=2,a3=1,a2=3, this is an invalid permutation because ap1 equals p3;
- a3=1,a1=2,a2=3, this is an invalid permutation because ap2 equals p3;
- a2=3,a3=1,a1=2, this is an invalid permutation because ap2 equals p3;
- a3=1,a2=3,a1=2, this is an invalid permutation because ap1 equals p3.
Therefore, there is no valid permutation.
Constraints
- For the first 20% of the testdata, 1≤n≤10.
- For the first 40% of the testdata, 1≤n≤15.
- For the first 60% of the testdata, 1≤n≤1000.
- For the first 80% of the testdata, 1≤n≤105.
- For 100% of the testdata, 1≤n≤5×105, 0≤ai≤n, 1≤wi≤109, and the sum of all wi does not exceed 1.5×1013.
Translated by ChatGPT 5