AcWing 788. 逆序对的数量
原题链接
简单
作者:
自动AC姬
,
2024-11-29 15:05:01
,
所有人可见
,
阅读 8
#include <iostream>
#include <random>
using namespace std;
#define MaxSize 100010
typedef long long ElemType;
ElemType sum = 0;
ElemType B[MaxSize];
void Merge(ElemType A[], int low, int mid, int high){
int tempSum = 0;
for(int i = low;i <= high;i ++)
B[i] = A[i]; // A先往B复制
int i = low, j = mid + 1;
int k = low;
while(i <= mid && j <= high){
if(B[i] <= B[j]) A[k ++] = B[i ++];
else{
sum += (mid - i + 1); // 由已得的排列知有这么多个在j之前且>B[j]的元素
A[k ++] = B[j ++];
}
}
while(i <= mid) A[k ++] = B[i ++];
while(j <= high) A[k ++] = B[j ++];
}
void MergeSort(ElemType a[], int low, int high){
if(low < high){
int mid = (low + high) / 2;
MergeSort(a, low, mid);
MergeSort(a, mid + 1, high);
Merge(a, low, mid, high);
}
}
int main(){
ElemType arr[MaxSize];
int n;
cin >> n;
for(int i = 0;i < n;i ++) cin >> arr[i];
MergeSort(arr, 0, n - 1);
cout << sum << endl;
return 0;
}