这个是和老师之外的另一种做法,便于理解原理
#include <iostream>
using namespace std;
typedef long long LL;
const int N = 100010;
int n, q[N], tmp[N];
LL merge_sort(int l, int r)
{
if (l >= r) return 0;
int mid = l + r >> 1;
LL res = merge_sort(l, mid) + merge_sort(mid + 1, r);
int i = l, j = mid + 1, k = 0;
while (i <= mid && j <= r)
{
if (q[i] <= q[j])
{
tmp[k ++] = q[i ++];
res += j - mid - 1;
}
else
{
tmp[k ++] = q[j ++];
}
}
while (i <= mid)
{
tmp[k ++] = q[i ++];
res += r - mid;
}
while (j <= r) tmp[k ++] = q[j ++];
for (int i = l, k = 0; i <= r; i ++, k ++)
{
q[i] = tmp[k];
}
return res;
}
int main()
{
cin >> n;
for (int i = 0; i < n; i ++)
{
scanf("%d", &q[i]);
}
cout << merge_sort(0, n - 1) << endl;
return 0;
}