A tree array is suitable for a single element to be modified frequently, and also to repeatedly ask for a range of
The efficiency of the programming of the tree array is higher than that of the segment tree (the time complexity is the same, but the constant of the dressing array is smaller)
If the change is not a number, but a range is not suitable for the tree array (less efficient)
A summary of the time complexity of a tree array:
Build array 0 (n)
Update 0 (LOGN)
Local summation 0 (LOGN)
When you want to query a sum (n) (for a[n), you can do this based on the following algorithm:
Step1: Make sum = 0, turn the second step;
Step2: If n <= 0, the algorithm ends, returns the sum value, otherwise sum = sum + Cn, turn to the third step;
Step3: Make n = N–lowbit (n), go to the second step.
It can be seen that this algorithm is to add this interval and all together, why is the efficiency is log (n)? The following gives proof:
n = n–lowbit (n) This step is actually equivalent to subtracting the last 1 of the binary of N. The binary of n has a maximum of log (n) 1, so the query efficiency is log (n).
So modify, modify a node, must modify all its ancestors, the worst case is to modify the first element, up to log (n) ancestors.
So the modification algorithm is as follows (to a node I plus x):
Step1: When i > N, the algorithm ends, otherwise turns the second step;
Step2:ci = Ci + x, i = i + lowbit (i) go to the first step.
i = i +lowbit (i) This process is actually just a process of filling the end 1 with 0.
The tree array is too fast for the sum of the arrays!
Note:
Suggested formula for Lowbit (x):
Lowbit (x): =x and (x xor (x-1));
or Lowbit (x): =x and (-X);
The following question is attached
hdu4911
#include <bits/stdc++.h>
#define N 100100
typedef __int64 LL;
int n;
ll K, ans;
int a[n], b[n], c[n];
int lowbit (int x) {
return x & (-X);
}
void Add (int x) {
for (; x <= n; x + = Lowbit (x)) {
c[x]++;
}
}
int sum (int x) {
int res = 0;
for (; x > 0; X-= Lowbit (x)) {
Res + = C[x];
}
return res;
}
int main () {
int I, J;
while (~SCANF ("%d%i64d", &n, &k)) {
for (i = 1; I <= n; i++) {
scanf ("%d", &a[i]);
B[i] = A[i];
}
memset (c, 0, sizeof (c));
Sort (b + 1, B + n + 1);
Ans = 0;
for (i = 1; I <= n; i++) {
Forwarditer Lower_bound (forwarditer First, Forwarditer last,const _tp& val) algorithm returns a non-descending sequence [first, last] The position of the first greater than or equal to Val in the value.
j = Lower_bound (b + 1, B + n + 1, a[i])-B;
Ans + = SUM (n)-sum (j);
Add (j);
}
if (ans > k)
printf ("%i64d\n", ans-k);
Else
printf ("0\n");
}
return 0;
}
Tree-like array of data structures