Analysis of permutations considering inversions and gaps
Python
Hard
lists
Task «Analysis of permutations considering inversions and gaps»
Given a permutation of numbers from 1 to n. It is required to determine whether it is "almost identity": the number of inversions (pairs i<j where a[i] > a[j]) must be equal to the maximum possible for permutations with a fixed number of breaks. A break is a position k where a[k] != k. If the permutation satisfies the condition, output the number of breaks, otherwise output -1. Additionally, if the number of breaks is 0, output 0. If the permutation is impossible (e.g., the data is invalid), output -2.
Input Format
In the first line, an integer n (1 ≤ n ≤ 10^5). In the second line, n integers — a permutation.
Output Format
One integer: the number of breaks, -1 or -2.
Examples
Example 1
INPUT
abacaba
abacaba
OUTPUT
7
Example 2
INPUT
3
3 2 1
OUTPUT
-1
main.py