The tree array in this question is a little characteristic, that is, the so-called discretization is required. It seems mysterious to start to hear this name, but it is actually very simple.
It is to convert the value of an array arr into a group of continuous values, because their order remains unchanged, and the result is not affected.
For example: 9 1 0 5 4-> to: 5 2 1 4 3 to see their relative position unchanged.
9 and 5 are the maximum values in the first position, 1 and 2 are the second largest values in the second position, and 0 and 1 are in the first position. Do you see the corresponding order?
That's a simple method called discretization.
If you are familiar with counting sort, it is no effort to understand and write programs.
Of course, it would be better to use Merge Sorting, but merging is too simple.
Http://poj.org/problem? Id = 2299
We use a tree array to add the discretization mentioned above.
Class UltraQuickSort2299 {const static int SIZE = 500005; int * reflect, * tree; inline int lowbit (int x) {return x & (-x);} void update (int x, int val, int len) {while (x <= len) {tree [x] + = val; x + = lowbit (x) ;}} long query (int x) {long ans = 0; while (x> 0) {ans + = tree [x]; x-= lowbit (x);} return ans ;} struct Node {int val, pos; bool operator <(const Node a) const {return val <. val ;}}; Node * arr; public: UltraQuickSort2299 (): arr (Node *) malloc (sizeof (Node) * SIZE), tree (int *) malloc (sizeof (int) * SIZE )), reflect (int *) malloc (sizeof (int) * SIZE) {int N; while (scanf ("% d", & N) & N! = 0) {for (int I = 1; I <= N; I ++) {scanf ("% d", & arr [I]. val); arr [I]. pos = I;} std: sort (arr + 1, arr + N + 1); for (int I = 1; I <= N; I ++) {reflect [arr [I]. pos] = I; // the so-called discretization, that is, corresponding to the new value, the relative position remains unchanged, and the subscript is remembered as the starting point of 1, so the reverse thinking leads to the thinking of counting sort} std:: fill (tree, tree + N + 1, 0); long ans = 0; for (int I = 1; I <= N; I ++) {update (reflect [I], 1, N); ans + = I-query (reflect [I]);} printf ("% lld \ n ", ans );}}~ UltraQuickSort2299 () {free (tree); free (arr); free (reflect );}};