AcWing 107. 超快速排序
原题链接
简单
作者:
Value
,
2020-04-25 10:02:32
,
所有人可见
,
阅读 614
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 500010;
typedef long long ll;
int a[N], backup[N];
int n;
ll merge_sort(int q[], int l, int r){
if(l == r) return 0;
int mid = l + r >> 1;
ll res = merge_sort(q, l, mid) + merge_sort(q, mid + 1, r);
int i = l, j = mid + 1, k = 0;
while(i <= mid && j <= r){
if(q[i] <= q[j]) backup[k++] = q[i++];
else{
res += mid - i + 1;
backup[k++] = q[j++];
}
}
while(i <= mid) backup[k++] = q[i++];
while(j <= r) backup[k++] = q[j++];
for(i = l, k = 0; i <= r; i ++, k ++ ){
q[i] = backup[k];
}
return res;
}
int main(){
while(cin >> n && n != 0){
for(int i = 0; i < n; i ++ ) scanf("%d", &a[i]);
cout << merge_sort(a, 0, n-1) << endl;
}
return 0;
}