POJ3468 A Simple Problem with Integers 线段树区间更新

POJ3468 A Simple Problem with Integers

/*线段树区间更新
2000MS   4484K	
*/
#include <stdio.h>
#include <string.h>
const int MAX=1e5+5;
long long tree[MAX*4];
long long lazy[MAX*4];//延时数组
void read(int &x)//读入优化
{
    long long f=1;x=0;char s=getchar();
    while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
    while(s>='0'&&s<='9'){x=x*10+s-'0';s=getchar();}
    x*=f;
}
void pushup (int root)//向上更新
{
    tree[root]=tree[root*2]+tree[root*2+1];
}
void pushdown (int root,int left,int right,int mid)//向下更新
{
    tree[root*2]+=lazy[root]*(mid-left+1);
    tree[root*2+1]+=lazy[root]*(right-mid);
    lazy[root*2]+=lazy[root];
    lazy[root*2+1]+=lazy[root];
    lazy[root]=0;
}
void build (int root,int left,int right)//建树
{
    lazy[root]=0;
    if (left==right)
    {
        int x;
        read(x);
        tree[root]=x;
        return ;
    }
    int mid=(left+right)/2;
    build(root*2,left,mid);
    build(root*2+1,mid+1,right);
    pushup(root);
}
void update (int root,int left,int right,int L,int R,int val)//区间更新
{
    if (L<=left&&R>=right)
    {
        tree[root]+=(right-left+1)*val;
        lazy[root]+=val;
        return ;
    }
    int mid=(right+left)/2;
    if (lazy[root]!=0) pushdown(root,left,right,mid);
    if (L<=mid) update(root*2,left,mid,L,R,val);
    if (R>mid) update(root*2+1,mid+1,right,L,R,val);
    pushup(root);
}
long long query (int root,int left,int right,int L,int R)//区间查询
{
    if (L<=left&&R>=right)
        return tree[root];
    int mid=(right+left)/2;
    long long sum=0;
    if (lazy[root]!=0) pushdown(root,left,right,mid);
    if (L<=mid) sum+=query(root*2,left,mid,L,R);
    if (R>mid) sum+=query(root*2+1,mid+1,right,L,R);
    return sum;
}
int main ()
{
    int n,m;
    read(n);read(m);
    build(1,1,n);
    while (m--)
    {
        int x,y,z;
        char c;
        c=getchar();
        if (c=='Q')
        {
            read(x);read(y);
            printf ("%I64d\n",query(1,1,n,x,y));//long long 64位
        }
        else
        {
            read(x);read(y);read(z);
            update(1,1,n,x,y,z);
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/nrtostp/article/details/80148966