問題一覧 > 通常問題

No.1604 Swap Sort:ONE

レベル : / AI推定難易度 : 900 / 実行時間制限 : 1ケース 2.000秒 / メモリ制限 : 512 MB / 標準ジャッジ問題
タグ : (解説公開後に AC するまで非表示) / 解いたユーザー数 180
作問者 : SPD_9X2 / テスター : FSM penguinman
お気に入りにしたユーザー ProblemId : 6370 / 自分の提出
問題文最終更新日: 2021-07-14 17:30:17
This statement was translated by AI (claude-opus-5-5, effort medium) and may contain errors or differ in nuance from the original. The original statement takes precedence. Back to the original
yukicoder contest 304 (順位表) の他の問題:

Problem Statement

You are given a permutation $P$ of the integers $1$ to $N$. The $i$-th term of the permutation $P$ is denoted by $P_i$.

You may repeat the following operation any number of times, possibly $0$ times.

  • Choose integers $i$,$j$ $\left( 1 \le i < j \le N\right)$ satisfying $|P_i - P_j| \le 1$, and swap the values of $P_i$ and $P_j$.

Determine whether $P$ can be made into a monotonically increasing sequence, and if it is possible, find the minimum number of operations.

Here, $P$ is said to be a monotonically increasing sequence if $P_i < P_{i+1}$ holds for all $i \left( 1 \le i < N\right)$.

Input

$N$
$P_1\ P_2\ ...\ P_N$

  • All input values are integers.
  • $2 \le N \le 3000$
  • $1 \le P_i \le N$
  • Every integer $i \left(1 \le i \le N\right)$ appears exactly $1$ time in $P$.

Output

If the sequence cannot be made monotonically increasing no matter how many operations are performed, print $-1$.

Otherwise, print the minimum number of operations required to make it monotonically increasing.

Print a newline at the end.

Sample

Sample 1
Input
3
3 2 1
Output
3

$\left(3,2,1\right)$ → $\left(2,3,1\right)$ → $\left(1,3,2\right)$ → $\left(1,2,3\right)$
achieves it in $3$ operations. It cannot be made monotonically increasing in fewer operations, so print $3$.

Sample 2
Input
5
1 2 3 4 5
Output
0

The sequence is monotonically increasing from the start.

Sample 3
Input
10
1 3 7 2 10 9 8 4 5 6
Output
17

提出するには、Twitter 、GitHub、 Googleもしくは右上の雲マークをクリックしてアカウントを作成してください。