当前位置: 代码迷 >> 综合 >> (区间更新lazy)POJ3468 A Simple Problem with Integers
  详细解决方案

(区间更新lazy)POJ3468 A Simple Problem with Integers

热度:84   发布时间:2023-11-02 21:51:47.0

传送门:(区间更新lazy)POJ3468 A Simple Problem with Integers

模板题。

代码:

#include<iostream>
#include<cstdio>
using namespace std;
const int maxn=1e5+10;
int a[maxn];
typedef long long ll;struct Tree{int l,r;ll sum,lazy;void update(int x){lazy+=x;sum+=1LL*(r-l+1)*x;}
}tree[maxn<<2];
int n,q;void push_up(int x){tree[x].sum=tree[x<<1].sum+tree[x<<1|1].sum;
}void push_down(int x){int lazyval=tree[x].lazy;if(lazyval){tree[x<<1].update(lazyval);tree[x<<1|1].update(lazyval);tree[x].lazy=0;}
}void build(int x,int l,int r){tree[x].l=l,tree[x].r=r;tree[x].sum=tree[x].lazy=0;if(l==r){tree[x].sum=a[l];return ;}int mid=l+((r-l)>>1);build(x<<1,l,mid);build(x<<1|1,mid+1,r);push_up(x);
}void update(int x,int l,int r,int val){int L=tree[x].l,R=tree[x].r;if(l<=L&&R<=r){tree[x].update(val);return ;}push_down(x);int mid=L+((R-L)>>1);if(mid>=l) update(x<<1,l,r,val);if(mid<r) update(x<<1|1,l,r,val);push_up(x);
}ll query(int x,int l,int r){int L=tree[x].l,R=tree[x].r;if(l<=L&&R<=r) return tree[x].sum;push_down(x);ll ans=0;int mid=L+((R-L)>>1);if(mid>=l) ans+=query(x<<1,l,r);if(mid<r) ans+=query(x<<1|1,l,r);push_up(x);return ans;
}int main(){scanf("%d%d",&n,&q);for(int i=1;i<=n;i++){scanf("%d",&a[i]);}build(1,1,n);char op;int a,b;ll c;while(q--){scanf(" %c",&op);if(op=='Q'){scanf("%d%d",&a,&b);printf("%lld\n",query(1,a,b));}else{scanf("%d%d%lld",&a,&b,&c);update(1,a,b,c);}}return 0;
}

 

  相关解决方案