题目描述
模板题:逆序对数量
注意用long!!!!!
C++代码
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 1;
long merge_sort(int a[], int l, int r){
if(l >= r)
return 0;
int mid = l + r >> 1;
long res = merge_sort(a, l, mid) + merge_sort(a, mid + 1, r);
int k = 0, i = l, j = mid + 1;
int temp[r - l + 1];
while(i <= mid && j <= r){
if(a[i] <= a[j])
temp[k++] = a[i++];
else{
temp[k++] = a[j++];
res += mid - i + 1;
}
}
while(i <= mid)
temp[k++] = a[i++];
while(j <= r)
temp[k++] = a[j++];
k = 0;
for(int i = l; i <= r; i++)
a[i] = temp[k++];
return res;
}
int main(){
int a[N];
int n;
cin >> n;
for(int i = 0; i < n; i++)
cin >> a[i];
long res = merge_sort(a, 0, n - 1);
cout << res << "\n";
return 0;
}