Ultra-QuickSort
Time Limit: 7000MS | Memory Limit: 65536K | |
Total Submissions: 48348 | Accepted: 17652 |
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.
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
因为看的是《算法》的第二章排序的前几节,所以专门挑的排序的题来做的。这是一个求逆序对数的题,题意是给你多个序列,每个序列前都有他的序列的长度。是这样的:5(序列长度) 9 1 0 5 4(序列中的值) 3(序列长度) 1 2 3(序列中的值) …… 0(表示结束)。刚开始想直接暴力计算逆序对数,但担心超时,于是网上找了下别人的思路。原来归并排序可以求逆序对数,而且非常的优美和巧妙。
import java.util.Scanner;
/**
* Created by 小粤 on 2015/8/3.
*/
public class Main
{
private static int[] aux = new int[500000];
private static int[] numbers = new int[500000];
private static long counter = 0; // This counter must be long.
private static boolean less(int a, int b)
{
return a - b < 0;
}
private static void sort(int lo, int hi)
{
if (lo >= hi)
{
return;
}
int mid = (lo + hi) / 2;
sort(lo, mid);
sort(mid + 1, hi);
merge(lo, mid, hi);
}
private static void merge(int lo, int mid, int hi)
{
for (int k = lo; k <= hi; k++)
{
aux[k] = numbers[k];
}
int i = lo, j = mid + 1;
for (int k = lo; k <= hi; k++)
{
if (i > mid)
{
numbers[k] = aux[j++];
}
else if (j > hi)
{
numbers[k] = aux[i++];
}
else if (less(aux[j], aux[i]))
{
numbers[k] = aux[j++];
counter += mid - i + 1; // This is the core.
}
else
{
numbers[k] = aux[i++];
}
}
}
public static void main(String[] args)
{
int lengthOfNumbers = 0;
Scanner scanner = new Scanner(System.in);
while (true)
{
lengthOfNumbers = scanner.nextInt();
if (lengthOfNumbers != 0)
{
for (int i = 0; i < lengthOfNumbers; i++)
{
numbers[i] = scanner.nextInt();
}
counter = 0;
sort(0, lengthOfNumbers - 1);
System.out.println(counter);
}
else
{
break;
}
}
}
}