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
Solution:
The question is to exchange two adjacent columns in ascending order. The question is at least exchanged several times. This question is of the same type as the previous janan question, and both are reverse order pairs. The only difficulty is that the data is very large. The element value in the series can reach 999999999, and the tree array cannot be so large. However, since there are a maximum of 500000 columns, Discretization can be performed to compress the elements in the series to 1. Discretization is to correspond the input value to the subscript. It can be implemented using a struct. Then, the input values are sorted from small to large, and then stored in an array. The answer is beyond the int range and must be stored in int64 format.
AC code:
# Include <iostream> # include <cstdio> # include <algorithm> # include <cstring> using namespace STD; const int maxn = 500005 ;__ int64 C [maxn]; struct node {int A, B; // a stores the input value, and B stores its coordinates} p [maxn]; bool CMP (node v, node s) {return v. A <S. a;} int lowbit (int A) {return a & (-A);} void Update (int A) {While (A <maxn) {c [a] + = 1; A + = lowbit (a) ;}__ int64 sum (int A) {_ int64 sum = 0; while (a> 0) {sum + = C [a]; A-= lowbit (a);} return sum;} int main () {int n, a [maxn]; _ int64 ans; while (scanf ("% d", & N) {ans = 0; memset (C, 0, sizeof (c); For (INT I = 1; I <= N; I ++) {scanf ("% d", & P [I]. a); P [I]. B = I;} Sort (p + 1, P + n + 1, CMP); For (INT I = 1; I <= N; I ++) // discretization A [p [I]. b] = I; for (INT I = 1; I <= N; I ++) {ans + = I-sum (A [I])-1; // It Must Be-1, because the number of elements before the input value is updated (A [I]);} printf ("% i64d \ n", ANS );} return 0 ;}