#P10068. [CCO 2023] Line Town

[CCO 2023] Line Town

Problem Description

The NN residents of Line Town are standing in a line. Initially, from left to right, their happiness values are h1,h2,,hNh_{1}, h_{2}, \ldots, h_{N}.

You are the mayor of Line Town, and you are carrying out your plan called "Community, Candy, and Organization" (CCO). Therefore, you have the power to swap residents' positions. In one swap, you may swap two adjacent residents in the line. However, this swap will flip (negate) the happiness values of both residents.

You want to know whether it is possible to perform some swaps so that the residents' happiness values, from left to right, are in non-decreasing order. If it is possible, output the minimum number of swaps required.

Input Format

The first line contains an integer NN.

The second line contains NN integers h1,,hNh_{1}, \ldots, h_{N}, representing the residents' happiness values from left to right.

Output Format

Output one integer on a single line: the minimum number of swaps. If the task is impossible, output 1-1.

6
-2 7 -1 -8 2 8
3
4
1 -1 1 -1
-1

Hint

Sample Explanation 1

You can perform 33 swaps as follows:

  • Swap the 2nd and 3rd residents, and the happiness values become [2,1,7,8,2,8][-2,1,-7,-8,2,8].
  • Swap the 4th and 5th residents, and the happiness values become [2,1,7,2,8,8][-2,1,-7,-2,8,8].
  • Swap the 3rd and 4th residents, and the happiness values become [2,1,2,7,8,8][-2,1,2,7,8,8].

The residents are now in non-decreasing order of happiness values as required. It is impossible to achieve a non-decreasing arrangement with fewer than 33 swaps.

Sample Explanation 2

There is no sequence of swaps that can make the residents arranged in non-decreasing order of happiness values.

Constraints

For all testdata, 1N5×1051 \leq N \leq 5\times 10^5, 109hi109-10^{9} \leq h_{i} \leq 10^{9}.

  • Additional Constraint A: For all ii, hi=1\left|h_{i}\right| = 1.
  • Additional Constraint B: For all ii, hi1\left|h_{i}\right| \leq 1.
  • Additional Constraint C: For all iji \neq j, hihj\left|h_{i}\right| \neq\left|h_{j}\right|.
Subtask ID Score Range of NN Additional Constraint
1 12 1N20001 \leq N \leq 2000 A
2 1N5×1051 \leq N \leq 5\times 10^5
3 1N20001 \leq N \leq 2000 B
4 16 1N5×1051 \leq N \leq 5\times 10^5
5 1N20001 \leq N \leq 2000 C
6 12 1N5×1051 \leq N \leq 5\times 10^5
7 8 1N20001 \leq N \leq 2000
8 12 1N5×1051 \leq N \leq 5\times 10^5

Translated by ChatGPT 5