题目地址:
https://www.acwing.com/problem/content/description/109/
在这个问题中,您必须分析特定的排序算法----超快速排序。该算法通过交换两个相邻的序列元素来处理
n
n
n个不同整数的序列,直到序列按升序排序。对于输入序列9 1 0 5 4
,超快速排序生成输出0 1 4 5 9
。您的任务是确定超快速排序需要执行多少交换操作才能对给定的输入序列进行排序。
输入格式:
输入包括一些测试用例。
每个测试用例的第一行输入整数
n
n
n,代表该用例中输入序列的长度。
接下来
n
n
n行每行输入一个整数
a
i
a_i
ai,代表用例中输入序列的具体数据,第
i
i
i行的数据代表序列中第
i
i
i个数。
当输入用例中包含的输入序列长度为
0
0
0时,输入终止,该序列无需处理。
输出格式:
对于每个需要处理的输入序列,输出一个整数
o
p
op
op,代表对给定输入序列进行排序所需的最小交换操作数,每个整数占一行。
数据范围:
0
≤
n
<
500000
0≤n<500000
0≤n<500000
一个测试点中,所有
n
n
n的和不超过
500000
500000
500000。
0
≤
a
i
≤
999999999
0≤a_i≤999999999
0≤ai≤999999999
答案就是逆序对的数量,求逆序对数量可以用归并排序。代码如下:
#include <iostream>
using namespace std;
using ll = long long;
const int N = 5e5 + 10;
int n;
int a[N], b[N];
ll merge_sort(int l, int r) {
ll res = 0;
if (l >= r) return res;
int mid = l + r >> 1;
res += merge_sort(l, mid) + merge_sort(mid + 1, r);
int i = l, j = mid + 1, idx = l;
while (i <= mid && j <= r) {
if (a[i] <= a[j])
b[idx++] = a[i++];
else
res += mid - i + 1, b[idx++] = a[j++];
}
while (i <= mid) b[idx++] = a[i++];
while (j <= r) b[idx++] = a[j++];
for (int i = l; i <= r; i++) a[i] = b[i];
return res;
}
int main() {
while (scanf("%d", &n) && n) {
for (int i = 1; i <= n; i++) scanf("%d", &a[i]);
printf("%lld\n", merge_sort(1, n));
}
}
每组数据时间复杂度 O ( n log n ) O(n\log n) O(nlogn),空间 O ( n ) O(n) O(n)。