CCO '23 P3 - Line Town

View as PDF

Submit solution


Points: 30 (partial)
Time limit: 2.0s
Memory limit: 1G

Author:
Problem types
Canadian Computing Olympiad: 2023 Day 1, Problem 3

The N residents of Line Town have arranged themselves in a line. Initially, the residents have happiness values of h_{1}, h_{2}, \ldots, h_{N} from left to right along the line.

Since you are the mayor of Line Town, you are implementing the third pillar of your plan entitled "Community, Candy, and Organization" (CCO). As such, you have taken the mayoral power to swap the residents' locations. In one swap, you may tell two adjacent residents to swap their positions in the line. However, this swap will cause both residents to negate their happiness values.

You would like to perform some swaps so that the residents' happiness values are in nondecreasing order from left to right in the line. Determine whether this is possible, and if so, the minimum number of swaps needed.

Input Specification

The first line of input contains a single integer N.

The next line of input contains N integers h_{1}, \ldots, h_{N} (-10^{9} \le h_{i} \le 10^{9}), the happiness values of the residents from left to right.

Marks AwardedBounds on NBounds on h_{i}
3 marks1 \le N \le 2\,000|h_{i}| = 1 for all i
3 marks1 \le N \le 500\,000|h_{i}| = 1 for all i
3 marks1 \le N \le 2\,000|h_{i}| \le 1 for all i
4 marks1 \le N \le 500\,000|h_{i}| \le 1 for all i
4 marks1 \le N \le 2\,000|h_{i}| \ne |h_{j}| for all i \ne j
3 marks1 \le N \le 500\,000|h_{i}| \ne |h_{j}| for all i \ne j
2 marks1 \le N \le 2\,000No additional constraints.
3 marks1 \le N \le 500\,000No additional constraints.

Output Specification

On a single line, output the minimum number of swaps, or -1 if the task is impossible.

Sample Input 1

6
-2 7 -1 -8 2 8

Output for Sample Input 1

3

Explanation of Output for Sample Input 1

It is possible to perform 3 swaps as follows:

  1. Swap the 2\text{nd} and 3\text{rd} resident so that the line becomes [-2, 1, -7, -8, 2, 8].
  2. Swap the 4\text{th} and 5\text{th} resident so that the line becomes [-2, 1, -7, -2, 8, 8].
  3. Swap the 3\text{rd} and 4\text{th} resident so that the line becomes [-2, 1, 2, 7, 8, 8].

The residents are now arranged in non-decreasing order of happiness values as required. No non-decreasing arrangement can be obtained with less than 3 swaps.

Sample Input 2

4
1 -1 1 -1

Output for Sample Input 2

-1

Explanation of Output for Sample Input 2

There is no sequence of swaps that will place residents in non-decreasing order of happiness values.


Comments

There are no comments at the moment.