在这个问题中,您必须分析特定的排序算法----超快速排序。
该算法通过交换两个相邻的序列元素来处理n个不同整数的序列,直到序列按升序排序。
对于输入序列9 1 0 5 4,超快速排序生成输出0 1 4 5 9。
您的任务是确定超快速排序需要执行多少交换操作才能对给定的输入序列进行排序。
输入格式
输入包括一些测试用例。
每个测试用例的第一行输入整数n,代表该用例中输入序列的长度。
接下来n行每行输入一个整数aiai,代表用例中输入序列的具体数据,第i行的数据代表序列中第i个数。
当输入用例中包含的输入序列长度为0时,输入终止,该序列无需处理。
输出格式
对于每个需要处理的输入序列,输出一个整数op,代表对给定输入序列进行排序所需的最小交换操作数,每个整数占一行。
数据范围
0≤N<5000000≤N<500000,
0≤ai≤9999999990≤ai≤999999999
输入样例:
5
9
1
0
5
4
3
1
2
3
0
输出样例:
6
0
归并排序求逆序对个数经典题
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N=500005;
int a[N],b[N];
ll ans=0;
const int MOD=1e9+7;
//归并排序
//将有二个有序数列a[first...mid]和a[mid...last]合并。
void mergearray(int a[],int first,int mid,int last,int temp[])
{int i=first,j=mid+1;int n=mid,m=last;int k=0;while(i<=n&&j<=m){if(a[i]<=a[j]){temp[k++]=a[i];i++;}else{temp[k++]=a[j];ans+=mid-i+1;j++;}}while(i <= n)temp[k++] = a[i++];while (j <= m)temp[k++] = a[j++];for (i = 0; i < k; i++)a[first + i] = temp[i];//out(a,k+first);
}
//递归版本
void mergesort(int a[], int first, int last, int temp[])
{if (first < last){int mid = (first + last) >>1;mergesort(a, first, mid, temp); //左边有序mergesort(a, mid + 1, last, temp); //右边有序mergearray(a, first, mid, last, temp); //再将二个有序数列合并}
}int main()
{int n;while(scanf("%d",&n)!=-1){if(n==0)break;ans=0;for(int i=1; i<=n; i++)scanf("%d",&a[i]);mergesort(a,1,n,b);cout<<ans<<endl;}return 0;
}