QOJ.ac

QOJ

Time Limit: 2 s Memory Limit: 256 MB Total points: 100

#22490. Cow Photographs

Statistics

Farmer John wants to take a picture of his entire herd of $N$ ($1 \le N \le 100,000$) cows conveniently numbered 1..$N$ so he can show off to his friends.

On picture day, the cows run to form a single line in some arbitrary order with position i containing cow $c_{i}$ ($1 \le c_{i} \le N$). Farmer John has his own ideas about how the cows should line up.

FJ thinks cow $i$ may stand only to the left of cow $i+1$ (for all $i$, $1 \le i \le N-1$) and that cow $N$ may only stand to the left of Cow 1. Of course, no cow will stand to the left of the first (leftmost) cow in the line.

The cows are hungry for the promised post-photo dinner, so Farmer John wants to take the picture as quickly as possible. Cows are not great at following directions, so he will only choose a pair of adjacent cows and have them switch places once per minute. How quickly is Farmer John able to get them into some acceptable order?

Consider a set of 5 cows whose initial lineup looks like this:

     Left           Right
        3  5  4  2  1

He can first swap the second pair of cows:

        3  4  5  2 1

and then swap the rightmost pair:

        3  4  5  1  2

to yield an acceptable lineup that required but two minutes of cow swapping.

Input

  • Line 1: A single integer: $N$
  • Lines $2..N+1$: Line $i+1$ contains the number of the i-th cow in line: $c_{i}$

Output

  • Line 1: The minimum amount of time, in minutes, that it takes Farmer John to get the cows into some appropriate order.

Examples

Input 1

5
3
5
4
2
1

Output 1

2

Problem credits: Travis, 2010

Discussions

About Discussions

The discussion section is only for posting: General Discussions (problem-solving strategies, alternative approaches), and Off-topic conversations.

This is NOT for reporting issues! If you want to report bugs or errors, please use the Issues section below.

Open Discussions 0
No discussions in this category.

Issues

About Issues

If you find any issues with the problem (statement, scoring, time/memory limits, test cases, etc.), you may submit an issue here. A problem moderator will review your issue.

Guidelines:

  1. This is not a place to publish discussions, editorials, or requests to debug your code. Issues are only visible to you and problem moderators.
  2. Do not submit duplicated issues.
  3. Issues must be filed in English or Chinese only.
Active Issues 0
No issues in this category.
Closed/Resolved Issues 0
No issues in this category.