[模板] 归并排序
作者:互联网
[模板] 归并排序
#include <bits/stdc++.h>
using namespace std;
long long cnt = 0;
int a[1000000+7],b[1000000+7];
void merge_sort(int l,int r){
if(l >= r) return;///必须>=,因为mid+1可能会大于
int mid = (l+r)/2;
merge_sort(l,mid);
merge_sort(mid+1,r);
int i = l,j = mid+1,k = l;
while(i<=mid && j<=r){
if(a[i]<=a[j])
b[k++] = a[i++];
else
b[k++] = a[j++],cnt+=mid-i+1;///表示从i到mid的数字都大于a[j]都要算一遍
}
while(i<=mid)
b[k++] = a[i++];
while(j<=r)
b[k++] = a[j++];
memcpy(a+l,b+l,(r-l+1)*sizeof(int));
}
int main(){
std::ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
int n;
cin>>n;
for(int i = 0;i<n;i++)
cin>>a[i];
merge_sort(0,n-1);
cout<<cnt<<'\n';
return 0;
}
标签:sort,归并,int,mid,1000000,merge,long,排序,模板 来源: https://www.cnblogs.com/BlankYang/p/16265215.html