poj 2299 求逆序数

时间:2023-12-10 11:32:44
 #include <iostream>
const int MAX = ;
int a[MAX];
int swap[MAX]; //临时数组
int n; //数组a的长度
__int64 result; //数组a中的逆序数 //归并两个已经有序的段:a[low]—a[mid]和a[mid+1]—a[high],使得a[low]—a[high]有序。
void merge(int low, int mid, int high)
{
int i = low;
int j = mid + ;
int m = ;
while(i <= mid && j <= high)
{
if(a[i] <= a[j])
{
swap[m++] = a[i];
i++;
}
else
{
swap[m++] = a[j];
j++;
result += mid - i + ;
}
}
while(i <= mid)
{
swap[m++] = a[i];
i++;
}
while(j <= mid)
{
swap[m++] = a[j];
j++;
}
for(i = ; i < m; i++)
a[low + i] = swap[i];
} //归并排序:对a[low]—a[high]进行归并排序。
void mergeSort(int low, int high)
{
int mid;
if(low < high)
{
mid = (low + high) /;
mergeSort(low, mid);
mergeSort(mid + , high);
merge(low, mid, high);
}
} int main()
{
int i;
while(true)
{
scanf("%d",&n);
if(n == ) break;
result = ;
for(i = ; i < n; i++)
scanf("%d",a+i);
mergeSort(, n-);
printf("%I64d\n",result);
}
return ;
}