线段树区间查询区间更新

来源:互联网 发布:华为手机全球销量知乎 编辑:程序博客网 时间:2024/03/29 14:22

模板

#include<iostream>#include<cstdio>#include<algorithm>#include<cstring>using namespace std;#define lson rt<<1,l,mid#define rson rt<<1|1,mid+1,rconst int maxn=100000+100;struct node{    int l,r,val,lazy;}tree[maxn*4];void push_up(int rt){    tree[rt].val=tree[rt<<1].val+tree[rt<<1|1].val;}void push_down(int rt,int mid){    if(tree[rt].lazy)    {        tree[rt<<1].lazy+=tree[rt].lazy;        tree[rt<<1|1].lazy+=tree[rt].lazy;        tree[rt<<1].val+=tree[rt].lazy*(mid-(mid>>1));        tree[rt<<1|1].val+=tree[rt].lazy*(mid>>1);        tree[rt].lazy=0;        }}void build(int rt,int l,int r){    tree[rt].l=l;    tree[rt].r=r;    tree[rt].lazy=0;    if(l==r)    {        scanf("%d",&tree[rt].val);        return;    }    int mid=(l+r)/2;    build(lson);    build(rson);    push_up(rt);}void update(int rt,int l,int r,int w){    if(tree[rt].l==l&&tree[rt].r==r)    {        tree[rt].lazy+=w;        tree[rt].val+=(r-l+1)*w;        return;    }       push_down(rt,tree[rt].r-tree[rt].l+1);    int mid=(tree[rt].l+tree[rt].r)/2;    if(l>mid)    {        update(rt<<1|1,l,r,w);    }    else if(mid>=r)    {        update(rt<<1,l,r,w);    }    else    {        update(lson,w);        update(rson,w);    }    push_up(rt);}int query(int rt,int l,int r){    if(tree[rt].l==l&&tree[rt].r==r)    {        return tree[rt].val;    }    push_down(rt,tree[rt].r-tree[rt].l+1);    int res=0;      int mid=(tree[rt].l+tree[rt].r)/2;    if(l>mid)    {        res+=query(rt<<1|1,l,r);    }    else if(mid>=r)    {        res+=query(rt<<1,l,r);    }    else     {        res+=query(lson);        res+=query(rson);       }    return res;}int main (){    int n,m;    while(~scanf("%d %d",&n,&m))    {        build(1,1,n);        while(m--)        {            char ch[2];            scanf("%s",ch);            int a,b,c;            if(ch[0] == 'Q')            {                scanf("%d %d", &a,&b);                printf("%d\n",query(1,a,b));            }            else            {                scanf("%d %d %d",&a,&b,&c);                update(1,a,b,c);            }        }    }    return 0;} 
原创粉丝点击