(Template) Fenwick tree

-------------------------------------------------- --------------------- ----------------------- front eye - ------------------------------------------------

ll data [500003]; // deposit point data
ll sub [500003]; // data array of differential
ll tree [500003]; // tree [i] represents the date [i-lowbit (i) +1] + .. . + data [i]

 

// x represents the binary representation of the first from right to left into a decimal number 1

inline int lowbit(int x){       
    return x&(-x);
}

A single point of modification, the query interval

// achievements

void build(){      
    for(int i=1;i<=n;i++){
        for(int j=i;j<=n;j+=lowbit(j)){
            tree[j]+=data[i];
        }
    }
}   

 

// single-point update

void add(int x,int d){      
    while(x<=n){
        tree[x]+=d;
        x+=lowbit(x);    
    }
}

 

// query interval

inline int range_query(int l,int r){    
    int ans1=0,ans2=0;
    for(int i=r;i>0;i-=lowbit(i)){
        ans1+=tree[i];
    }
    for(int i=l-1;i>0;i-=lowbit(i)){
        ans2+=tree[i];
    }
    return ans1-ans2;
}

Modify the interval, a single point of inquiry

// array of achievements with a difference

void build(){      
    for(int i=1;i<=n;i++){
        for(int j=i;j<=n;j+=lowbit(j)){
            tree[j]+=sub[i];
        }
    }
}   

 

// modify the interval

void range_add(int l,int r,int d){      
    for(int i=l;i<=n;i+=lowbit(i)){
        tree[i]+=d;
    }
    for(int i=r+1;i<=n;i+=lowbit(i)){
        tree[i]-=d;
    }
}

 

// a single point of inquiry

inline int query(int x){
    int ans=0;
    for(int i=x;i>0;i-=lowbit(i)){
        ans+=tree[i];
    }
    return ans;
}

 

Guess you like

Origin www.cnblogs.com/xiaozezz/p/11773699.html