Ultra-quicksort
Time limit:7000 Ms |
|
Memory limit:65536 K |
Total submissions:39436 |
|
Accepted:14214 |
Description
In this problem, you have to analyze a particle 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 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 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
59105431230
Sample output
60
Question: calculate the number of reverse sequences.
Analysis: sort by merge.
(Specific algorithm: http://blog.csdn.net/fyxz1314/article/details/37604005)
Code:
# Include <stdio. h >#include <iostream >#include <algorithm> using namespace STD; # define Max 510000 # define m limit int A [Max]; int L [Max], R [Max]; __int64 sum; void merge (int l, int M, int R) {int N1, N2; int I, j, k; n1 = m-L + 1; // number of elements from L to M n2 = r-m; // number of elements from m + 1 to R for (I = 1; I <= N1; I ++) // copy the left element of L to m to the L array L [I] = A [L + I-1]; for (I = 1; I <= n2; I ++) // copy the right elements from m + 1 to R [I] = A [M + I] in the r array; L [N1 + 1] = m; // store "Sentinel" at the bottom to avoid blank comparison. M is relatively large. R [n2 + 1] = m; I = 1; j = 1; for (k = L; k <= r; k ++) // copy the smallest elements in the two stacks to array a each time, and combine them into an ordered sequence {If (L [I] <= R [J]) {A [k] = L [I]; I ++;} else {A [k] = R [J]; j ++; sum + = (n1-i + 1) ;}} void mergesort (int l, int R) {int m; If (L <r) {M = (L + r) /2; mergesort (L, M); mergesort (m + 1, R); merge (L, M, R) ;}} int main () {int N, I, j; while (~ Scanf ("% d", & N) & n! = 0) {sum = 0; for (I = 0; I <n; I ++) scanf ("% d", & A [I]); mergesort (0, n-1); printf ("% i64d \ n", sum);} return 0 ;}