[Data structure learning] block and Fenwick tree

Partition and Fenwick tree all have important applications in the interval problem

emm array block not as efficient as the tree, but the idea of ​​comparing miss

Said first block:

The information sequence is divided into n number of sqrt (n) blocks, each block data to pre-accelerate the subsequent query of section information

The first piece of code:

const int maxn = 5e5 + 50;
int sum[maxn],a[maxn],l[maxn],r[maxn],belong[maxn];
int block,num;

void build(){
    block = sqrt(n);
    num = n/block; if(n%block) num++;
    for(int i = 1; i <= num; i++)
        l[i] = (i-1)*block+1, r[i] = i*block;
    r[num] = n;

    for(int i = 1; i <= num; i++){
        for(int j = l[i]; j <= r[i]; j++)
            belong[j] = i, sum[i] += a[j];
    }
}

Global variable code requires preprocessing of these are: sum [i] denotes the i-th block and the data (or exclusive and also be a product of this kind, the same)

a [i] for the i-th data, l [i], r [i], respectively, about the i-th block index endpoint, belong block [i] belongs to the i-th storage

After pretreatment, labeled single-point modification / update and query the code section:

inline void update(int x, int y){
    a[x] += y;
    sum[belong[x]] += y;
}

inline int query(int x, int y){
    int ans = 0;
    if(belong[x] == belong[y]){
        for(int i = x; i <= y; i++)
            ans += a[i];
        return ans;
    }
    for(int i = x; i <= r[belong[x]]; i++)
        ans += a[i];
    for(int i = belong[x] + 1; i < belong[y]; i++)
        ans += sum[i];
    for(int i = l[belong[y]]; i <= y; i++)
        ans += a[i];
    return ans;
}

Wherein the single point array data updates to a change in the data, then the sum of the subscripts x block belongs to increase y

And the query interval [x, y], and, block here is summed violence

1. When x, y when the same block, traversing summation

2. When x, y is not in the same block, traversing x to x summation block belongs to a right boundary, plus sum [x + 1] to the sum [y-1], then summing y traverse the left edge of the block belongs to y

Are time complexity O (sqrt (n)) modified to a single point O (1)

 

qwq first wrote this, Fenwick tree again tomorrow to write summary

Guess you like

Origin www.cnblogs.com/leafsblogowo/p/12668906.html