Returns the number of reverse orders in a tree array.
Sample input:
3
1 2 3
4
4 3 2 1
Sample output:
0
6
# Include <stdio. h> # include <iostream> # include <string. h ># include <algorithm> using namespace STD; int A [10005]; int N; int lowbit (INT t) {return T & (-T );} void Update (int I, int d) // update the number of arrays containing X {While (I <= N) {A [I] + = D; I + = lowbit (I) ;}} int getsum (int I) // calculate the number of rows smaller than X {int sum = 0; while (I> 0) {sum + = A [I]; I-= lowbit (I);} return sum;} int main () {int I, K; while (CIN> N) {memset (A, 0, sizeof (a); int ans = 0; for (I = 1; I <= N; I ++) {CIN> K; // insert data to the tree array one by one update (k, 1); ans + = I-getsum (k); // I-getsum (k) indicates a number larger than K, that is, the number of reverse orders} cout <ans <Endl;} return 0 ;}
Discrete operation + tree Array
Sample input:
5
9 1 0 5 4
Discrete operation process:
1. Structured Storage:
K: 9 1 0 5 4
Orde: 1 2 3 4 5
2. After sorting:
K: 0 1 4 5 9
Orde: 3 2 5 4 1
3. Save to array:
A [3] = 1;
A [2] = 2;
A [5] = 3;
A [4] = 4;
A [1] = 5;
4. Final result:
I: 1 2 3 4 5
A [I]: 5 2 1 4 3
Original input: 9 1 0 5 4
Discrete: 5 2 1 4 3
# Include <stdio. h> # include <iostream> # include <string. h ># include <algorithm> using namespace STD; int A [10005]; // Save the int C [10005] array after discretization; // save the tree array int N; struct node {int K, Orde;} p [1, 10005]; bool CMP (node A, Node B) {return (. k <B. k);} int lowbit (INT t) {return T & (-T);} void Update (int I, int d) {While (I <= N) {c [I] + = D; I + = lowbit (I) ;}} int getsum (int I) {int sum = 0; while (I> 0) {sum + = C [I]; I-= lowbit (I);} return sum;} int main () {int I, j; while (CIN> N) {for (I = 1; I <= N; I ++) {CIN> P [I]. k; P [I]. orde = I;} // discretization sort (p + 1, P + n + 1, CMP); for (I = 1; I <= N; I ++) A [p [I]. orde] = I; memset (C, 0, sizeof (c); int ans = 0; For (j = 1; j <= N; j ++) {update (A [J], 1); ans + = J-getsum (A [J]);} cout <ans <Endl;} return 0 ;}