AcWing 5909. 车厢重组
原题链接
简单
作者:
GeorgeLMLM
,
2024-09-29 18:19:57
,
所有人可见
,
阅读 11
容易发现:交换次数 = 逆序对数量,用归并排序
#include<iostream>
using namespace std;
const int N = 100010;
int n;
int q[N],tmp[N];
int m_sort(int l,int r)
{
if(l >= r) return 0;
int mid = l + r >> 1;
int res = 0;
res = m_sort(l,mid) + m_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++];
else{
tmp[k++] = q[j++];
res += mid - i + 1;
}
}
while(i <= mid) tmp[k++] = q[i++];
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()
{
scanf("%d",&n);
for(int i = 0 ; i < n ; i ++) scanf("%d",&q[i]);
printf("%d",m_sort(0,n - 1));
return 0;
}