POJ2299

#include <iostream>
#include <stdio.h>
#include <string.h>

using namespace std;
long long int res;
long long int num[500000 + 5];
long long int ans[500000 + 5];

void memeryarray( long long int a[], int first , int last, int mid,long long  int ans[])
{
   long long  int m = mid ;
   long long  int i = first;
   long long  int j = mid + 1;
   long long  int k = 0;

    while( i <= m && j <= last)
    {
        if(a[i] <= a[j])
             ans[k++] = a[i++];
        else
        {
            res += m- i + 1;
            ans[k++] = a[j++];
        }
    }

    while(j <= last)
      ans[k++] = a[j++];
    while( i <= m)
      ans[k++] = a[i++];

    for( int l = 0; l < k; l++)
     a[first + l] = ans[l];

}


void memerysort(long long int a[], int first, int last,long long int ans[])
{
    if(first < last)
    {
        long long int mid = (first+last)/2;

        memerysort(a, first, mid, ans);
        memerysort(a, mid+1, last, ans);

        memeryarray(a, first, last, mid , ans);
    }


}


int main()
{
    long long int n;
    while(scanf("%I64d",&n)!=EOF,n)
    {
        res = 0;
        for( int i = 0; i<n; i++)
         scanf("%lld",&num[i]);
        memset(ans,0,sizeof(ans));
        memerysort(num,0,n-1,ans);
        printf("%lld\n",res);
    }
    return 0;
}

你可能感兴趣的:(POJ2299)