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: Multiple Input groups. Input n, n = 0 to end, and then enter n numbers. A few steps are required to sort the input number in order.
Idea: Since the number of inputs is not an incremental sequence with a tolerance of 1 starting from 1, first use two fast Arrays for conversion. It will be OK if you place them in the tree array!
AC code:
# Include <stdio. h> # include <iostream> # include <string. h ># include <algorithm> using namespace STD; long D1 [5000000]; int N; struct node // G memory, h memory subscript {int g, h ;} s [5000000]; int CMP (struct node A, struct Node B) // controls the direction of sorting from large to small {return. g> B. g;} int CMP1 (struct node A, struct Node B) // control the sorting direction from small to large {return. h <B. h;} int lowbit (int x) {return X & (-x);} long sum (int x) // sum of tree arrays, this question is how many numbers exist before X, because all numbers are converted to an incremental sequence with a tolerance of 1. And is the answer {long res = 0; while (x> 0) {res + = D1 [X]; X-= lowbit (x);} return res ;} void add (int x) // update the tree Array {While (x <= N) {D1 [x] ++; x + = lowbit (x );}} int main () {int A, B, I, J; long num; while (scanf ("% d", & N )! = EOF) {If (n = 0) break; num = 0; memset (D1, 0, sizeof (D1); for (I = 1; I <= N; I ++) {scanf ("% d", & S [I]. g); s [I]. H = I;} Sort (S + 1, S + n + 1, CMP); // sort by G value for (I = 1; I <= N; I ++) s [I]. G = I; sort (S + 1, S + n + 1, CMP1); // sort by H, that is, the original subscript for (I = 1; I <= N; I ++) {num + = sum (s [I]. g); // Add the number of the previous number, that is, add (s [I]. g) ;}printf ("% LLD \ n", num );}}
Poj 2299 ultra-quicksort (tree array)