The use of tree arrays is faster.
Tree array difficulties:
1. How to traverse the tree
2. How to Use array data
Create a tree array. The red part represents all tree array nodes.
Basic operations:
Find the calculation of the next node. If you do not understand the functions of the following functions, check the negative memory storage problem.
In short, the memory is put in reverse + 1; this function can be used to find their single-parent nodes and brother nodes, such as 6-> 8, 6-> 4 or 7-> 8, 7-> 6.
This is the key to implementing a tree array. If we understand how to traverse such a tree, we will use this data structure.
inline int lowbit(int x){return x & (-x);//or return x&(x^(x-1));}
Update node:
void update(int i, int val, int len){while (i <= len){c[i] += val;i += lowbit(i);}}
Sum operation:
int getsum(int x){int ans = 0;while (x > 0){ans += c[x];x -= lowbit(x);}return ans;}
The main thing is to look at the picture, and then think about it yourself. Let's look at the code.
Code to solve this problem:
Class MinimumInversionNumber_3_TreeArray {static const int SIZE = 5005; int * a, * c; // General array and tree array inline int lowbit (int x) {return x & (-x ); // or return x & (x ^ (x-1);} void update (int I, int val, int len) {while (I <= len) {c [I] + = val; I + = lowbit (I) ;}} int getsum (int x) {int ans = 0; while (x> 0) {ans + = c [x]; x-= lowbit (x);} return ans;} public: MinimumInversionNumber_3_TreeArray (): a (int *) malloc (sizeof (int) * SIZ E), c (int *) malloc (sizeof (int) * SIZE) {int n, t; while (~ Scanf ("% d", & n) {for (int I = 1; I <= n; I ++) {scanf ("% d", & t ); a [I] = t + 1;} // memset (c, 0, sizeof (c); it is best not to use memset to set the initial value fill (c, c + n + 1, 0); int res = 0; for (int I = 1; I <= n; I ++) {update (a [I], 1, n ); res + = I-getsum (a [I]); // so far, how many digits are less than or equal to a [I] getsum (a [I]), therefore, the number I-getsum (a [I]) greater than a [I] is the number of reverse orders} int ans = res; for (int I = 2; I <= n; I ++) {res + = n-2 * a [I-1] + 1; if (res <ans) ans = res;} printf ("% d \ N ", ans );}}~ MinimumInversionNumber_3_TreeArray () {free (a); free (c );}};