poj 2299

终于写了个mergesort  偷懒不行啊

#include <iostream>
using namespace std;
int a[500001];
int temp[500001];
__int64 sum;
void merge(int l,int m,int r)
{
    int p = 0;
    int i = l;
    int j = m+1;
    while(i<=m && j<=r)
    {
         if(a[i]>a[j])
         {
               temp[p++] = a[j++];
               sum += m-i+1;
         }
         else
         temp[p++] = a[i++];
    }
    while(i<=m)temp[p++] = a[i++];
    while(j<=r)temp[p++] = a[j++];
    for(i=0;i<p;i++)a[l+i] = temp[i]; 
}
void mergesort(int l,int r)
{
     int m;
     if(l<r)
     {
         m = (l+r)/2;   
         mergesort(l,m);
         mergesort(m+1,r);
         merge(l,m,r);
     }
}
int main()
{
    int n;
    int i;
    while(cin>>n && n !=0)
    {
          sum = 0;i=0;
          while(i<n)cin>>a[i++];
          mergesort(0,n-1);
          cout<<sum<<endl;
    }
}
posted @ 2011-06-17 21:19  dapanshe  阅读(133)  评论(0编辑  收藏  举报