#P5552. Exam Paper Distribution

    ID: 18782 Type: Default 1000ms 256MiB

Exam Paper Distribution

Exam Paper Distribution

During an exam, all students (girls) are seated in a row with positions numbered \(1 \sim n\). The distance between positions \(i\) and \(j\) is given by \(|i - j|\). Each exam paper bears a number which indicates the seat of the student who is to receive it.

The teacher, ygg, distributes the exam papers and is initially positioned at \(s\). All exam papers are initially held in the teacher's left hand, arranged in a stack with the order given by \(p\) (the first element represents the top of the stack). The teacher uses both hands to distribute the papers in the following manner:

  • The teacher removes the top exam from his left hand using his right hand. If this happens to be the last paper, he moves directly to the designated student’s seat and delivers it.
  • If there are still papers in the left hand, he then compares the distance from his current position to the student indicated on the left-hand paper (which is now at the top) and the distance to the student indicated on the paper in his right hand. If \(\left|current - (left\ hand's paper)\right|\) is strictly less than \(\left|current - (right\ hand's paper)\right|\), he places the right-hand paper at the bottom of the left-hand stack. Otherwise, he immediately delivers the paper from his right hand by moving to the corresponding seat and updating his current position.
  • This process is repeated: after each comparison (or forced delivery in case of the last paper), the teacher picks the next exam from his left hand and continues until all papers are delivered.

Your task is to calculate the total distance the teacher travels to deliver all exam papers.

inputFormat

The first line contains two integers \(n\) and \(s\), where \(n\) is the number of exam papers and \(s\) is the teacher's initial position.

The second line contains \(n\) integers representing the sequence \(p\), where the first integer is the top of the stack.

outputFormat

Output a single integer representing the total distance the teacher travels while distributing all the exam papers.

sample

3 4
2 6 6
6