Children
InterviewTime limit1sMemory limit128 MB
Given a permutation on n cells, find the fewest adjacent swaps so every walk visits all cells.
Problem
On the playground a rectangle of unit width and length is drawn and divided into square cells. Each cell holds one natural number between and , and all of the numbers are different (so together they form a permutation of through ). At the start one child stands on each cell. Every minute each child walks to the cell whose number is written on the cell it is currently standing on.
The children grow bored and start thinking about a different question. They want that, over the course of the whole game, every child eventually stands on every cell. To make this happen they may swap the numbers written on two adjacent cells (two cells that sit next to each other in the row). Redrawing the digits takes time, so they want to make as few swaps as possible. Find the minimum number of swaps needed.
Input
The first line contains one integer (), the number of square cells. The second line contains integers (), where is the number written on the -th cell. All values are distinct, so they form a permutation of through .
Output
Print a single integer: the minimum number of swaps the children must make.
Hint
In the case where and the cells read , it is enough to swap the numbers on cells and . After that a child starting on cell moves and thereby visits every cell, so the minimum number of swaps is .