AT_arc225_d.Gap Swap (easy)

提高+/省选-

通过率:0%

时间限制:2.00s

内存限制:1024MB

AC君温馨提醒

该题目为【atcoder】题库的题目,您提交的代码将被提交至atcoder进行远程评测,并由ACGO抓取测评结果后进行展示。由于远程测评的测评机由其他平台提供,我们无法保证该服务的稳定性,若提交后无反应,请等待一段时间后再进行重试。

题目描述

This problem has a similar setting to Problem E, but the cost of the operation is different.

There is a permutation PP of (1,2,…,N)(1,2,\ldots,N). You can perform the following operation on PP.

  • Choose integers ii and jj satisfying 1≤i<j≤N1 \le i < j \le N. Here, Pk=kP_k=k must hold for every integer kk satisfying i<k<ji < k < j. Then, swap PiP_i and PjP_j.
    This operation incurs a cost of j−i\boldsymbol{j-i}.

Note that if i+1=ji+1=j, there is no integer kk satisfying i<k<ji<k<j, so the operation can always be performed. Therefore, there always exists a sequence of operations that sorts PP into ascending order.

Find the minimum total cost required to sort PP into ascending order.

本题的设定与问题 E 类似,但操作的代价不同。

给定一个 (1,2,…,N)(1,2,\ldots,N) 的排列 PP。你可以对 PP 执行以下操作:

  • 选择满足 1≤i<j≤N1 \le i < j \le N 的整数 ii 和 jj,要求对每个满足 i<k<ji < k < j 的整数 kk,均有 Pk=kP_k = k。然后交换 PiP_i 和 PjP_j。
    此操作的代价为 j−i\boldsymbol{j-i}。

注意:若 i+1=ji+1=j,则不存在满足 i<k<ji<k<j 的整数 kk,因此该操作总可执行。故总存在一系列操作能将 PP 排序为升序。

求将 PP 排序为升序所需的最小总代价。

输入格式

The input is given from Standard Input in the following format:

NN
P1P_1 P2P_2 …\ldots PNP_N

输入从标准输入给出,格式如下:

NN
P1P_1 P2P_2 …\ldots PNP_N

输出格式

Output the answer.

输出答案。

输入输出样例

  • 输入#1

    6
    6 2 3 5 4 1

    输出#1

    6
  • 输入#2

    3
    1 2 3

    输出#2

    0

说明/提示

Sample 1 Explanation:
For example, by performing two operations as follows, PP can be sorted into ascending order with a total cost of 66.

  • First operation: choose i=4,j=5i=4, j=5, and swap P4,P5P_4, P_5. This costs 11.
  • Second operation: choose i=1,j=6i=1, j=6, and swap P1,P6P_1, P_6. This costs 55.

PP cannot be sorted into ascending order with a cost less than 66, so the answer is 66.

Sample 2 Explanation:
The required total cost can be 00.

Constraints

  • 2≤N≤5×1052 \le N \le 5\times 10^5
  • 1≤Pi≤N1 \le P_i \le N
  • PP is a permutation of (1,2,…,N)(1,2,\ldots,N).
  • All input values are integers.

样例 1 解释:
例如,通过执行以下两次操作,可将 PP 排序为升序,总代价为 66。

  • 第一次操作:选择 i=4,j=5i=4, j=5,交换 P4P_4 与 P5P_5。此次操作代价为 11。
  • 第二次操作:选择 i=1,j=6i=1, j=6,交换 P1P_1 与 P6P_6。此次操作代价为 55。

无法以小于 66 的总代价将 PP 排序为升序,因此答案为 66。

样例 2 解释:
所需总代价可以为 00。

约束条件

  • 2≤N≤5×1052 \le N \le 5\times 10^5
  • 1≤Pi≤N1 \le P_i \le N
  • PP 是 (1,2,…,N)(1,2,\ldots,N) 的一个排列。
  • 所有输入值均为整数。

输入解题思路,AI测评打分。不知道怎么写?

首页