思想:分治
与快排的区别:快排是自顶向下,归并是自下而上.
模板
<模板题>
参考代码如下,注意开long long 最长是一个累加从1 到 10 0000,超过了int的范围.
#include<cstdio>
using namespace std;
const int N=1000010;
int q[N],tmp[N];
long long merge_sort(int q[],int l,int r){
if(l>=r) return 0;
int mid = l + r >> 1;
long long ans=merge_sort(q,l,mid)+merge_sort(q,mid+1,r);
int k=0,i=l,j=mid+1;
while(i<=mid && j <=r){
if(q[i]<=q[j]) tmp[k++]=q[i++];
else{
tmp[k++]=q[j++];
ans+=mid-i+1;
}
}
while(i<=mid) tmp[k++]=q[i++];
while(j<=r) tmp[k++]=q[j++];
for(i=l,j=0;i<=r;i++,j++) q[i]=tmp[j];
return ans;
}
int main(){
int n;
scanf("%d",&n);
for(int i=1;i<=n;i++){
scanf("%d",&q[i]);
}
printf("%lld\n",merge_sort(q,1,n));
return 0;
}