AcWing 5958. 光荣的梦想
原题链接
简单
作者:
拼凑回忆
,
2025-01-11 21:19:03
,
所有人可见
,
阅读 1
#include <iostream>
#include <algorithm>
using namespace std;
const int N = 1e5 + 10;
long long ret = 0;
int a[N], f[N];
//归并排序
void merge_sort(int q[], int l, int r)
{
if (l >= r) return;
int mid = l + r >> 1;
merge_sort(q, l, mid);
merge_sort(q, mid + 1, r);
//经过之后mid两边都是有序的
int k = 0, i = l, j = mid + 1;
while (i <= mid && j <= r)
if (q[i] <= q[j]) f[k++] = q[i++];
else f[k++] = q[j++], ret += mid - i + 1;
//如果i处的数大于j处的,那么必然i~mid的也都大于j,所以与j匹配的就有mid - i + 1;
while (i <= mid) f[k++] = q[i++];
while (j <= r) f[k++] = q[j++];
for (int i = l, j = 0; i <= r; i++, j++) q[i] = f[j];
}
int main()
{
int n;
cin >> n;
for (int i = 1; i <= n; i++)
cin >> a[i];
merge_sort(a, 1, n);
cout << ret;
return 0;
}