给定一个长度为 n的整数数列,请你计算数列中的逆序对的数量。
逆序对的定义如下:对于数列的第 i个和第 j个元素,如果满足 i<j且 a[i]>a[j],则其为一个逆序对;否则不是。
输入样例:
6
2 3 4 5 6 1
输出样例:
5
#include <iostream>
using namespace std;
int n;
const int N = 100000;
int q[N],temp[N];
typedef long long LL;
LL merge_sort(int l, int r)
{
if (l >= r)
return 0;
int mid = (l + r) / 2;
int k = 0, i = l, j = mid+1;
LL res;
res = merge_sort(l, mid) + merge_sort(mid + 1, r);
while (i <= mid && j <= r)
if (q[i] <= q[j])
temp[k++] = q[i++];
else
{
temp[k++] = q[j++];
res += mid - i + 1;
}
while (i <= mid)
temp[k++] = q[i++];
while (j <= r)
temp[k++] = q[j++];
for (int i = l, j = 0; i <= r; i++, j++)
q[i] = temp[j];
return res;
}
int main()
{
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> q[i];
}
cout << merge_sort(0, n - 1)<< endl;
return 0;
}