题目描述
blablabla
样例
#include<iostream>
using namespace std;
//定义long long 类型为LL
typedef long long LL;
const int N = 100010;
int q[N],tmp[N];
LL merge_sort(int q[], int l, int r)
{
if(l >= r) return 0;
int mid = l + r >> 1; // '+'运算顺序要高于'>>'
int i = l, j = mid + 1, k = 0;
//此时的res是mid左右两侧的数的逆序对数量之和
LL res = merge_sort(q, l, mid) + merge_sort(q, mid + 1, r);
while(i <= mid && j <= r)
{
if(q[i] <= q[j]) tmp[k++] = q[i++];
else
{
tmp[k++] = q[j++];
//mid-i+1是当逆序对的较大的数在mid左侧,较小的数在mid
//右侧时的逆序对数量
res += mid - i + 1;
}
}
//将剩下的数传到tmp数组中
while(i <= mid) tmp[k++] = q[i++];
while(j <= r) tmp[k++] = q[j++];
//将tmp的值传回给q数组,防止递归时少数。
for(int i = l, j = 0; i <= r, j < k; i++, j++)
{
q[i] = tmp[j];
}
//返回res逆序对的数量
return res;
}
int main()
{
int n;
scanf("%d",&n);
for(int i = 0; i < n; i++)
{
scanf("%d",&q[i]);
}
//逆序对数量
LL res = merge_sort(q, 0, n - 1);
cout << res << endl;
return 0;
}