QOJ.ac

QOJ

حد الوقت: 10 s حد الذاكرة: 1024 MB مجموع النقاط: 7

#12444. Reversort

الإحصائيات

Reversort 是一种将列表中的不同整数按升序排序的算法。该算法基于“反转”(Reverse)操作。每次应用此操作都会反转列表中某个连续部分的顺序。

该算法的伪代码如下:

Reversort(L):
 for i := 1 to length(L) - 1
 j := position with the minimum value in L between i and length(L), inclusive
 Reverse(L[i..j])

在 $i-1$ 次迭代后,列表的前 $i-1$ 个位置包含 $L$ 中最小的 $i-1$ 个元素,且按升序排列。在第 $i$ 次迭代期间,该过程会反转从第 $i$ 个位置到第 $i$ 个最小元素当前位置的子列表。这使得第 $i$ 个最小元素最终位于第 $i$ 个位置。

例如,对于一个包含 4 个元素的列表,该算法将执行 3 次迭代。以下是它处理 $L = [4, 2, 1, 3]$ 的过程:

  1. $i = 1, j = 3 \longrightarrow L = [1, 2, 4, 3]$
  2. $i = 2, j = 2 \longrightarrow L = [1, 2, 4, 3]$
  3. $i = 3, j = 4 \longrightarrow L = [1, 2, 3, 4]$

在我们的架构上执行该算法,最昂贵的部分是 Reverse 操作。因此,我们衡量每次迭代代价的方法就是传递给 Reverse 的子列表的长度,即 $j - i + 1$ 的值。整个算法的代价是每次迭代代价的总和。

在上面的例子中,各次迭代的代价依次为 3、1 和 2,总代价为 6。

给定初始列表,计算执行 Reversort 的代价。

输入格式

输入的第一行给出测试用例的数量 $T$。接下来是 $T$ 个测试用例。每个测试用例包含 2 行。第一行包含一个整数 $N$,表示输入列表中的元素数量。第二行包含 $N$ 个不同的整数 $L_1, L_2, \dots, L_N$,表示输入列表 $L$ 中的元素,按顺序排列。

输出格式

对于每个测试用例,输出一行 Case #x: y,其中 $x$ 是测试用例编号(从 1 开始),$y$ 是对给定输入列表执行 Reversort 的总代价。

数据范围

$1 \le T \le 100$ $2 \le N \le 100$ $1 \le L_i \le N$,对于所有 $i$ $L_i \neq L_j$,对于所有 $i \neq j$

样例

样例输入 1

3
4
4 2 1 3
2
1 2
7
7 6 5 4 3 2 1

样例输出 1

Case #1: 6
Case #2: 1
Case #3: 12

说明

样例 #1 已在题目描述中说明。

在样例 #2 中,只有一次迭代,其中 Reverse 被应用于大小为 1 的子列表。因此,总代价为 1。

在样例 #3 中,第一次迭代反转了整个列表,代价为 7。此后,列表已经排好序,但还有 5 次迭代,每次迭代的代价均为 1。

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.