GDUT_22级寒假训练专题五 H - 线段树 1

如题,已知一个数列,你需要进行下面两种操作:

  1. 将某区间每一个数加上 k

  1. 求出某区间每一个数的和。

Input

第一行包含两个整数 n,m,分别表示该数列数字的个数和操作的总个数。

第二行包含 n 个用空格分隔的整数,其中第 i 个数字表示数列第 i 项的初始值。

接下来 m 行每行包含 3 或 4 个整数,表示一个操作,具体如下:

  1. 1 x y k:将区间 [x,y] 内每个数加上 k

  1. 2 x y:输出区间 [x,y] 内每个数的和。

Output

输出包含若干行整数,即为所有操作 2 的结果。

线段树模板题

#include<iostream>
#include<cstdio>
#define l(x) tree[x].l
#define r(x) tree[x].r
#define sum(x) tree[x].sum
#define add(x) tree[x].add
using namespace std;
const int maxn=1000005;
struct node {
    int r,l;long long sum,add;
} tree[maxn];
long long s[maxn];
void build(int o,int l,int r) {
    l(o)=l;
    r(o)=r;
    if(l==r) {
        sum(o)=s[l];
    } else {
        int mid=(l+r)/2;
        build(o*2,l,mid);
        build(o*2+1,mid+1,r);
        sum(o)=sum(o*2)+sum(o*2+1);
    }
}
void pushdown(int o) {
    sum(o)+=add(o)*(r(o)-l(o)+1);add(o*2)+=add(o);add(o*2+1)+=add(o);add(o)=0;
}
int update(int l,int r,int o,long long k) {
//    cout<<o<<endl;
    if(l<=l(o)&&r>=r(o)) {
        add(o)+=k;
        int tot=k*(r(o)-l(o)+1);
        pushdown(o);
        return tot;
    } else {
        int tot=0;
        int mid=(l(o)+r(o))/2;
//        cout<<"mid="<<mid<<' '<<"l="<<l<<' '<<"r="<<r<<' '<<"l(o)="<<l(o)<<' '<<"r(o)="<<r(o)<<endl;
        if(l<=mid&&l(o)<=r)tot+=update(l,r,o*2,k);
        if(r>mid)tot+=update(l,r,o*2+1,k);
        sum(o)+=tot;
        return tot;
    }
}
long long query(int l,int r,int o) {
    if(l<=l(o)&&r>=r(o)) {
        pushdown(o);
        return sum(o);
    }
    int mid=(l(o)+r(o))/2;
    long long tot=0;
    pushdown(o);
    if(l<=mid&&l(o)<=r) {
        tot+=query(l,r,o*2);
    }
    if(mid<r) {
        tot+=query(l,r,o*2+1);
    }
    return tot;
}
int main() {
    int n,m;
    scanf("%d%d",&n,&m);
    for(int i=1; i<=n; i++)scanf("%lld",&s[i]);
    build(1,1,n);
    for(int i=1;i<=m;i++) {
        int a,b;long long c;
        scanf("%d",&a);
        if(a==1){scanf("%d%d%lld",&a,&b,&c);update(a,b,1,c);
//for(int i=1;i<=n*2;i++)cout<<i<<' '<<sum(i)<<endl;
}
        else {scanf("%d%d",&a,&b);printf("%lld\n",query(a,b,1));}
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值