n = int(input()) P = list(map(int, input().split())) sorted_values = sorted(P) # Split into blocks of consecutive values blocks = [] if sorted_values: current_min = sorted_values[0] current_max = sorted_values[0] for v in sorted_values[1:]: if v == current_max + 1: current_max = v else: blocks.append((current_min, current_max)) current_min = v current_max = v blocks.append((current_min, current_max)) # Create a list of blocks sorted by their minimum values sorted_blocks = sorted(blocks, key=lambda x: x[0]) # Map each value to its corresponding block index in sorted_blocks value_to_block = {} block_index = 0 for (min_val, max_val) in sorted_blocks: for v in range(min_val, max_val + 1): value_to_block[v] = block_index block_index += 1 # Check if the blocks in the original permutation are in the correct order current_block_order = [value_to_block[v] for v in P] prev_block = -1 for block_idx in current_block_order: if block_idx < prev_block: print(-1) exit() prev_block = block_idx # Group elements by their block block_elements = [[] for _ in range(len(sorted_blocks))] for v in P: block_idx = value_to_block[v] block_elements[block_idx].append(v) # Calculate total inversions in each block total_inversions = 0 for elements in block_elements: m = len(elements) inv = 0 for i in range(m): for j in range(i + 1, m): if elements[i] > elements[j]: inv += 1 total_inversions += inv print(total_inversions)