hdu 4267 A Simple Problem with Integers(线段树区间更新)

来源:互联网 发布:闻rush什么感觉 知乎 编辑:程序博客网 时间:2024/06/06 08:06

题目链接点这里

#include<stdio.h>#include<algorithm>#include<iostream>#define LL long longusing namespace std;const int N=110000;LL num[N];LL Sum;struct node{    LL l;    LL r;    LL sum;    LL add;}tree[N*4];LL n,q,i,j;void pushdown(LL x){    LL tmp=x<<1;    tree[tmp].add+=tree[x].add;    tree[tmp+1].add+=tree[x].add;    tree[tmp].sum+=tree[x].add*(tree[tmp].r-tree[tmp].l+1);    tree[tmp+1].sum+=tree[x].add*(tree[tmp+1].r-tree[tmp+1].l+1);    tree[x].add=0;}void build(int x,int y,int n){    tree[n].l=x;    tree[n].r=y;    tree[n].add=0;    if(x==y)    {        tree[n].sum=num[x];        return ;    }   // LL mid=(tree[n].l+tree[n].r)>>1;     int  mid=(x+y)>>1;    build(x,mid,2*n);    build(mid+1,y,2*n+1);    tree[n].sum=tree[n*2].sum+tree[n*2+1].sum;}void update(LL x,LL y,LL c,LL n){    if(y<tree[n].l||x>tree[n].r)        return ;    if(tree[n].l>=x&&tree[n].r<=y)    {        tree[n].add+=c;        tree[n].sum+=c*(tree[n].r-tree[n].l+1);        return ;    }    if(tree[n].add)     pushdown(n);    LL tmp=n<<1;    update(x,y,c,tmp);    update(x,y,c,tmp+1);    tree[n].sum=tree[n*2].sum+tree[n*2+1].sum;}void query(LL x,LL y,LL n){    if(y<tree[n].l||tree[n].r<x)        return ;    if(tree[n].l>=x&&tree[n].r<=y)    {       Sum+=tree[n].sum;       return ;    }     if(tree[n].add)     pushdown(n);    LL  mid=(tree[n].l+tree[n].r)>>1;    if(mid>=y)        query(x,y,2*n);    else if(mid<x)        query(x,y,2*n+1);    else    {        query(x,mid,2*n);        query(mid+1,y,2*n+1);    }}int main(){    LL x1,y1,c;    while(~scanf("%lld %lld",&n,&q))    {        for(i=1;i<=n;i++)        {            scanf("%lld",&num[i]);        }        build(1,n,1);        char s[2];        while(q--)        {            //Sum=0;            scanf("%s",s);            if(s[0]=='Q')            {                scanf("%lld%lld",&x1,&y1);                Sum=0;                query(x1,y1,1);                printf("%lld\n",Sum);            }            else if(s[0]=='C')            {                scanf("%lld%lld%lld",&x1,&y1,&c);                 update(x1,y1,c,1);            }        }    }    return 0;}
0 0
原创粉丝点击