求逆序对是归并排序的一个应用。
归并排序是将数列a[first,last]分成两半a[first,mid]和a[mid+1,last]分别进行归并排序,然后再将这两半合并起来。
合并的过程中(l<=i<=mid,mid+1<=j<=h),当a[i]<=a[j]时,不产生逆序数;当a[i]>a[j]时,在
前半部分中比a[i]大的数都比a[j]大,将a[j]放在a[i]前面的话,逆序数要加上mid+1-i。
下面是POJ2299的题解
#include <iostream>
#define SIZE 500005
using namespace std;
long long a[SIZE], temp[SIZE];
/**************归并算法**************/
long long cnt = 0;
void merge(long long *a, long long *temp, int first, int mid, int last){
int i = first, j = mid + 1;
int index = first;
while (i <= mid&&j <= last){
if (a[i] > a[j]){
temp[index++] = a[j];
j++;
cnt = cnt + mid - i + 1; //计算逆序对
}
else{
temp[index++] = a[i];
i++;
}
}
while (i <= mid)
temp[index++] = a[i++];
while (j <= last)
temp[index++] = a[j++];
for (int i = first; i <= last; i++)
a[i] = temp[i];
}
void mergeSort(long long *a, long long *temp, int first, int last){
if (first >= last)
return;
int mid = (first + last) / 2;
mergeSort(a, temp, first, mid);
mergeSort(a, temp, mid + 1, last);
merge(a, temp, first, mid, last);
}
int main()
{
int n;
while (cin >> n&&n){
for (int i = 1; i <= n; i++)cin >> a[i];
cnt = 0;
mergeSort(a, temp, 1, n);
cout << cnt << endl;
}
}