1. Tree array: Title: UVA1428
1 #include<iostream> 2 #include<algorithm> 3 #include<cstdio> 4 #include<string> 5 #include<cstring> 6 #include<numeric> 7 #include<vector> 8 #include<map> 9 #include<queue> 10 #include<set> 11 #include<cmath> 12 using namespace std; 13 typedef long long ll; 14 typedef pair<int,int>PII; 15typedef pair <ll, ll> PLL; 16 17 // The subscript of the tree array and the line segment tree are the same. The subscripts start from 1. . . This must not go wrong. . . 18 19 const int maxn = 1e5 + 10 ; 20 21 int tree [maxn + 10 ]; // Tree array. . . 22 int l [maxn + 10 ], r [maxn + 10 ]; 23 24 int lowbit ( int x) { // Solve the position of the last 1 in a binary number. . . 25 return x & ( -x); 26 } 27 // The sum of the tree array is different from the line tree, and the sum of the tree array may be added and subtracted every time. . . 28 29 int sum ( int x) { // Note that x is the index of the tree array. . . 30 int res = 0 ; 31 while (x> 0 ) { // Find the value of only the last 1 through lowbit, we only need to determine the existence of binary 1 and then continue the traversal operation. . . 32 res + = tree [x]; 33 x- = lowbit (x); // eg: x = 7 Then add 6 after that, add 4 after that, then x is 0, jump out of the loop. . . End the operation. . . 34 } 35 return res; // Find the sum directly. . 36 } 37 38 void add ( int x, int d) { //This step is to increase the operation. . . The operation is from the root of the tree to the top. . . 39 while (x < maxn) { 40 tree [x] + = d; // Add the current node. . . It is added from bottom to top. . . 41 x + = lowbit (x); // x is the index of the tree. . . 42 } 43 } 44 45 // l [i], r [i] records the number of digits smaller than the digits at position i. . . 46 47 int main () { 48 int T; 49 cin >> T; 50 ll ans; 51 while (T-- ) { 52 int a [maxn]; 53 int n; 54 cin>>n; 55 for(int i=1;i<=n;i++){ 56 cin>>a[i]; 57 } 58 memset(tree,0,sizeof(tree)); 59 memset(l,0,sizeof(l)); 60 for(int i=1;i<=n;i++){ 61 l[i]=sum(a[i]); 62 add(a[i],1);//个数均加一 63 } 64 memset(tree,0,sizeof(tree)); 65 memset(r,0,sizeof(r)); 66 for(int i=n;i>=1;i--){ 67 r[i]=sum(a[i]); 68 add(a[i],1); 69 } 70 ans=0; 71 for(int i=2;i<n;i++){ 72 ans=ans+l[i]*(n-r[i]-i)+r[i]*(i-1-l[i]); 73 } 74 cout<<ans<<endl; 75 } 76 77 return 0; 78 }