In this problem, you have to analyze a particular sorting algorithm. The algorithm processes a sequence of n distinct integers by swapping two adjacent sequence elements until the sequence is sorted in ascending order. For the input sequence
9 1 0 5 4 ,
Ultra-QuickSort produces the output
0 1 4 5 9 .
Your task is to determine how many swap operations Ultra-QuickSort needs to perform in order to sort a given input sequence.
Input
The input contains several test cases. Every test case begins with a line that contains a single integer n < 500,000 -- the length of the input sequence. Each of the the following n lines contains a single integer 0 <= a[i] <= 999,999,999, the i-th input sequence element. Input is terminated by a sequence of length n = 0. This sequence must not be processed.
Output
For every input sequence, your program prints a single line containing an integer numberop, the minimum number of swap operations necessary to sort the given input sequence.
Sample Input
5
9
1
0
5
4
3
1
2
3
0
Sample Output
60
在归并排序的分步骤里面添加一个计数步骤即可~数组元素和计数的count的类型都用long long,蛋疼 = =
代码:
#include <iostream>
#include <climits>
using namespace std;
long long merge(long long A[],int p,int q,int r)
{
int n1=q-p+1;
int n2=r-q;
long long count=0;
long long *L=new long long[n1+2];
long long *R=new long long[n2+2];
for(int i=1;i<=n1;i++)
L[i]=A[p+i-1];
for(int i=1;i<=n2;i++)
R[i]=A[q+i];
L[n1+1]=INT_MAX;
R[n2+1]=INT_MAX;
int i,j;
i=1;
j=1;
for(int k=p;k<=r;k++)
{
if(L[i]<=R[j])
{
count=count+j-1;
A[k]=L[i];
i++;
}
else
{
A[k]=R[j];
j++;
}
}
delete[]L;
delete[]R;
return count;
}
long long merge_sort(long long A[],int p,int r)
{
long long count=0;
if(p<r)
{
int q=(p+r)/2;
count=count+merge_sort(A,p,q);
count=count+merge_sort(A,q+1,r);
count=count+merge(A,p,q,r);
}
return count;
}
int main()
{
long long N;
while(cin>>N&&N!=0)
{
long long A[N];
long long count;
for(int i=1;i<=N;i++)
cin>>A[i];
count=merge_sort(A,1,N);
cout<<count<<endl;
}
return 0;
}