【题解】洛谷P1908逆序对 归并排序

题目链接
开long long,开long long,开long long……重要的事说三次,上次求逆序对没开long long 也炸了……不长记性

#include
#define _rep(i,x,y) for(int i=(x);i<=(y);i++)
const int N=5e5+10;
int n;
long long ans;
int a[N],b[N];
void merge_sort(int l,int r)
{
    if(l>=r)return;
    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])ans+=mid-i+1,b[k++]=a[j++];
    else b[k++]=a[i++];
    while(i<=mid)b[k++]=a[i++];
    while(j<=r)b[k++]=a[j++];
    _rep(o,l,r)a[o]=b[o];   
}
int main()
{
    //freopen("in.txt","r",stdin);
    scanf("%d",&n);
    _rep(i,1,n)scanf("%d",&a[i]);
    merge_sort(1,n);
    printf("%lld\n",ans);
    return 0;
}

你可能感兴趣的:(排序,归并排序)