线段树区间更新

#include 
using namespace std;
int n,tre[10003*4],int laz[10003*4];
void pushdown(int num){
    if(laz[num]!=0){
        tre[num*2]+=laz[num];
        tre[num*2+1]+=laz[num];
        laz[num*2]+=laz[num];
        laz[num*2+1]+=laz[num];
        laz[num]=0;
    }
}
void update(int num,int le,int ri,int x,int y){
    if(x<=le&&y>=ri){
        tre[num]++; laz[num]++; return ;
    }
    pushdown(num);
    int mid=(le+ri)/2;
    if(x<=mid) update(num*2,le,mid,x,y);
    if(y>mid) update(num*2+1,mid+1,ri,x,y);
}
int query(int num,int le,int ri,int x){
if(le==ri) return tre[num];
    pushdown(num);
    int mid=(le+ri)/2;
    if(x<=mid) return query(num*2,le,mid,x);
    else return query(num*2+1,mid+1,ri,x);
}
int main(void){
    while(scanf("%d",&n)==1&&n!=0){
        memset(tre,0,sizeof(tre));
        memset(laz,0,sizeof(laz));
        for(int i=0;i>a>>b;
            update(1,1,n,a,b);
        }
        for(int i=1;i<=n;i++){
            cout<

精简模板区间更新区间求和

#include 
using namespace std;
int n,tre[10003*4],laz[10003*4];
void pushdown(int num){
    tre[num*2]+=laz[num];
    tre[num*2+1]+=laz[num];
    laz[num*2]+=laz[num];
    laz[num*2+1]+=laz[num];
    laz[num]=0;
}
void update(int num,int le,int ri,int x,int y){
    if(x<=le&&y>=ri){
        tre[num]++; laz[num]++; return ;
    }
    pushdown(num);
    int mid=(le+ri)/2;
    if(x<=mid) update(num*2,le,mid,x,y);
    if(y>mid) update(num*2+1,mid+1,ri,x,y);
    tre[num]=tre[num*2]+tre[num*2+1];
}
int query(int num,int le,int ri,int x,int y){
    if(x<=le&&ri<=y) return tre[num];
    pushdown(num);
    int mid=(le+ri)/2;
    int ans=0;
    if(x<=mid)ans+=query(num*2,le,mid,x,y);
    if(y>mid)ans+=query(num*2+1,mid+1,ri,x,y);
    return ans;
}
int main(void){
    cin>>n;
    for(int i=1;i<=4;i++){
        int x,y;cin>>x>>y;
        update(1,1,5,x,y);
    }
    cout<

 

你可能感兴趣的:(ACM笔记-5代数)