A Simple Problem with Integers 【线段树】-区间加减求和

A Simple Problem with Integers
给出了一个序列,你需要处理如下两种询问。

“C a b c”表示给[a, b]区间中的值全部增加c (-10000 ≤ c ≤ 10000)。

“Q a b” 询问[a, b]区间中所有值的和。

Input
第一行包含两个整数N, Q。1 ≤ N,Q ≤ 100000.

第二行包含n个整数,表示初始的序列A (-1000000000 ≤ Ai ≤ 1000000000)。

接下来Q行询问,格式如题目描述。

Output
对于每一个Q开头的询问,你需要输出相应的答案,每个答案一行。

Sample Input
10 5
1 2 3 4 5 6 7 8 9 10
Q 4 4
Q 1 10
Q 2 4
C 3 6 3
Q 2 4
Sample Output
4
55
9
15
思路 模版题
代码

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<cmath>
#include<queue>
#include<stack>
#include<map>
#include<vector>
#include<set>
#define CLR(a,b) memset((a),(b),sizeof(a))
#define inf 0x3f3f3f3f
#define mod 100009
#define LL long long
#define M  5000000
#define ll o<<1
#define rr o<<1|1
#define lson o<<1,l,mid
#define rson o<<1|1,mid+1,r
using namespace std;
struct Tree
{
    LL l,r;
    LL len;
    LL sum;
    LL lazy;
}tree[M<<2];
void pushup(LL o)
{
     tree[o].sum=tree[rr].sum+tree[ll].sum;
}
void pushdown(LL o)
{
    if(tree[o].lazy)
    {
        tree[ll].lazy+=tree[o].lazy;
        tree[rr].lazy+=tree[o].lazy;
        tree[rr].sum+=tree[o].lazy*tree[rr].len;
        tree[ll].sum+=tree[o].lazy*tree[ll].len;
        tree[o].lazy=0;
    }
}
void build(LL o,LL l,LL r)
{
    tree[o].l=l;tree[o].r=r;
    tree[o].len=r-l+1;
    tree[o].lazy=0;
    if(r==l) 
    {
        LL a;
        scanf("%lld",&a);
        tree[o].sum=a;
        return;
     } 
     int mid=( l+r )>>1;
     build(lson);
     build(rson);
     pushup(o);
}
void update(LL o,LL l,LL r,LL val)
{
    if(l<=tree[o].l&&tree[o].r<=r) 
    {
        tree[o].lazy+=val;
        tree[o].sum+=val*tree[o].len;
        return;
    }
    pushdown(o);
    int mid=(tree[o].l+tree[o].r)>>1;
    if(r<=mid) update(ll,l,r,val);
    else if(l>mid) update(rr,l,r,val);
    else 
    {
        update(ll,l,mid,val);
        update(rr,mid+1,r,val);
     } 
    pushup(o);
}
LL query(LL o,LL l,LL r)
{
    if(tree[o].l>=l&&tree[o].r<=r) 
    return tree[o].sum;

    pushdown(o);

    int mid=(tree[o].l+tree[o].r)>>1;
    if(r<=mid) query(ll,l,r);
    else if(l>mid) query(rr,l,r);
    else return query(ll,l,mid)+query(rr,mid+1,r);
}
int main()
{
     LL n,q;
     while(~scanf("%lld%lld",&n,&q))
     {
         build(1,1,n);
     while(q--)
     {
        char c[2];
        scanf("%s",c);
        if(c[0]=='Q') 
        {
            LL x,y;
            scanf("%lld%lld",&x,&y);
            printf("%lld\n",query(1,x,y));
         }
         else 
         {
            LL a,b,c;
            scanf("%lld%lld%lld",&a,&b,&c);
            update(1,a,b,c);
         }
     }
     }
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值