归并排序求逆序数
View Code
#include <cstdio>
int left[250003], right[250003];
__int64 count;
void merge(int a[], int l, int m, int r)
{
int i, j, k, n1, n2;
n1 = m - l + 1;
n2 = r - m;
for (i = 0; i < n1; i++)
left[i] = a[l+i];
for (i = 0; i < n2; i++)
right[i] = a[m+i+1];
left[n1] = right[n2] = 0x7fffffff;
i = j = 0;
for (k = l; k <= r; k++)
{
if (left[i] <= right[j])
{
a[k] = left[i++];
}
else
{
a[k] = right[j++];
count += n1 - i;
}
}
}
void mergeSort(int a[], int l, int r)
{
if (l < r)
{
int m = (l + r) / 2;
mergeSort(a, l, m);
mergeSort(a, m+1, r);
merge(a, l, m, r);
}
}
int main()
{
int n, a[500001];
while (scanf("%d", &n) && n)
{
count = 0;
for (int i = 0; i < n; i++)
scanf("%d", &a[i]);
mergeSort(a, 0, n-1);
printf("%I64d\n", count);
}
}