Poj2299(归并排序)

归并排序

1.数组从0开始用

2.二分为(l+1<r)

3.cnt+=mid+j-k-1;

4.递归meger(0,n,a)

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;

typedef long long ll;

const ll nil=20000000000;
const int maxn=500000+10;
ll L[maxn/2],R[maxn/2];
int n;
ll a[maxn];

ll megersort(int l,int r,int mid,ll a[]){
   int n1=mid-l;
   int n2=r-mid;
   ll cnt=0;
   int i,j;
   for (i=0;i<n1;i++) L[i]=a[l+i];
   for (j=0;j<n2;j++) R[j]=a[mid+j];
   L[n1]=nil;
   R[n2]=nil;
   i=j=0;
   for (int k=l;k<r;k++){
        if(L[i]<=R[j]){
            a[k]=L[i++];
        }
        else {
            a[k]=R[j++];
            cnt+=mid+j-k-1;
        }
   }
  return cnt;
}

ll meger(int l,int r,ll a[]){
   if(l+1<r){
    int mid=(l+r)>>1;
    ll v1=meger(l,mid,a);
    ll v2=meger(mid,r,a);
    ll v3=megersort(l,r,mid,a);
    return v1+v2+v3;
   }
   else return 0;
}

int main(){
   // freopen("coo.out","w",stdout);
    while(scanf("%d",&n)&&n!=0){
        memset(a,0,sizeof(a));
        for (int i=0;i<n;i++) scanf("%d",&a[i]);
        printf("%lld\n",meger(0,n,a));
    }
return 0;
}

 

posted @ 2018-04-19 19:31  lmjer  阅读(199)  评论(0编辑  收藏  举报