#P8083. Maximizing Permutation Weight with Order Constraints

    ID: 21266 Type: Default 1000ms 256MiB

Maximizing Permutation Weight with Order Constraints

Maximizing Permutation Weight with Order Constraints

You are given two arrays \(A\) and \(B\) each of length \(N\). You may permute \(B\) arbitrarily to obtain a new array \(B'\) subject to the following order constraints:

  • For every \(i\) with \(1 \le i < N\): if \(A_i < A_{i+1}\) then \(B'_i < B'_{i+1}\).
  • For every \(i\) with \(1 \le i A_{i+1}\) then \(B'_i > B'_{i+1}\).

Define the weight of an array as \(\sum_{i=1}^{N-1} \left|B'_{i+1} - B'_i\right|\). Your task is to choose a permutation \(B'\) that satisfies the order constraints and maximizes the weight. Output both the maximum possible weight and one corresponding permutation \(B'\).

Note. In the above, all math formulas are in LaTeX format.

inputFormat

The input consists of three lines:

  1. The first line contains an integer \(N\) (the number of elements).
  2. The second line contains \(N\) space‐separated integers representing the array \(A\).
  3. The third line contains \(N\) space‐separated integers representing the array \(B\).

outputFormat

Output two lines. The first line contains the maximum weight. The second line contains \(N\) space‐separated integers representing a permutation \(B'\) that achieves this maximum weight while satisfying the order constraints.

sample

3
1 3 2
10 20 30
30

10 30 20

</p>