#include <stdio.h>
#include <stdlib.h>
#define WORD sizeof(long)
#define MAX_INT 0x7fffffff
long long reverse;
long array[2000010];
long left[1000010];
long right[1000010];
merge(long *arr, long p, long q, long r)
{
long i = 0, j = 0, total_len;
long nleft = q - p + 1;
long nright = r - q;
#if 0
long *left = malloc(WORD * (nleft + 1));
long *right = malloc(WORD * (nright + 1));
#endif
for (i=0 ; i<nleft ; i++)
{
left[i] = arr[p + i];
}
left[i] = MAX_INT;
for (i=0 ; i<nright ; i++)
{
right[i] = arr[q + 1 + i];
}
right[i] = MAX_INT;
total_len = nleft + nright + p;
i = j = 0;
for (; p<total_len ;p++)
{
if (left[i] <= right[j])
{
arr[p] = left[i++];
}
else
{
arr[p] = right[j++];
reverse += nleft - i; /*count reverse*/
}
}
#if 0
free(left);
free(right);
#endif
}
merge_sort(long *arr, long p, long r)
{
if (p < r)
{
long q = (p + r) / 2;
merge_sort(arr, p, q);
merge_sort(arr, q + 1, r);
merge(arr, p, q, r);
}
}
int main(int argc, char *argv[])
{
long N, i;
scanf("%ld", &N);
reverse = 0;
for (i=0 ; i<N ; i++)
{
scanf("%ld", &array[i]);
}
merge_sort(array, 0, N - 1);
printf("%lld\n", reverse);
}
|