利用归并排序统计逆序数,利用归并求逆序在对子序列s1和s2在归并时(s1,s2已经排好序),若s1[i]>s2[j](逆序状况),则逆序数加上s1.length-i,因为s1中i后面的数字对于s2[j]都是逆序的。
#include <stdio.h>
#include <stdlib.h>
int N;
int num[];
int tmp[];
__int64 count;
void Merge(int l,int mid,int r){
int i=l,j=mid+,k=;
while(i<=mid&&j<=r){
if(num[i]>num[j]) {
tmp[k++]=num[j++];
count+=mid-i+;
} else
{
tmp[k++]=num[i++];
}
}
while(i<=mid) tmp[k++]=num[i++];
while(j<=r) tmp[k++]=num[j++]; for(i=; i<k; i++)
{
num[l+i]=tmp[i];
}
}
void Mergesort(int l,int r){
int mid=(l+r)/;
if(l<r){
Mergesort(l,mid);
Mergesort(mid+,r);
Merge(l,mid,r);
}
}
int main(void) {
scanf("%d",&N);
int i=;
while(N){
for(i=;i<N;i++){
scanf("%d",&num[i]);
}
count=;
Mergesort(,N-);
printf("%I64d \n",count);
scanf("%d",&N);
} return EXIT_SUCCESS;
}
附:
Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 48082 | Accepted: 17536 |
Description
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.
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 number op, 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
6
0