1. 程式人生 > >歸並排序 逆序數

歸並排序 逆序數

lse ++ col rep 歸並排序 pre pan code urn

  很好理解:

int n,a[500010],c[500010];
long long ans;
void msort(int L,int R)
{
    if(L==R)return ;
    int mid=(L+R)>>1;
    msort(L,mid);
    msort(mid+1,R);
    int i=L,k=L,j=mid+1;
    while(i<=mid&&j<=R)
        if(a[i]<=a[j])
        c[k++]=a[i++];
        else
        c[k
++]=a[j++],ans+=mid-i+1; while(i<=mid) c[k++]=a[i++]; while(j<=R) c[k++]=a[j++]; rep(i,L,R) a[i]=c[i]; } int main() { int n; RI(n); rep(i,1,n) RI(a[i]); msort(1,n); cout<<ans; return 0; }

歸並排序 逆序數