线段树

此题以洛谷 P3372 线段树1 为例
主要是记录模板,就不多加解释

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
using namespace std;
typedef long long ll;
struct arr{
    int l,r,tag;ll sum;
}tree[500000];
int n,m,i,u;
inline int read(){
    int x=0,w=1;char ch=0;
    while(ch!='-'&&(ch<'0'||ch>'9')) ch=getchar();
    if(ch=='-') w=-1,ch=getchar();
    while(ch>='0'&&ch<='9')x=x*10+ch-48,ch=getchar();
    return x*w;
}
void build(ll p,ll l,ll r){
    tree[p].l=l;tree[p].r=r;
    if(l!=r) {
        int m=(l+r)>>1;
        build(p<<1,l,m);
        build((p<<1)+1,m+1,r);
    }
}
inline void push_down(ll p){
    if(tree[p].tag==0) return ;
    tree[p<<1].sum+=tree[p].tag*(tree[p<<1].r-tree[p<<1].l+1);
    tree[(p<<1)+1].sum+=tree[p].tag*(tree[(p<<1)+1].r-tree[(p<<1)+1].l+1);
    tree[p<<1].tag+=tree[p].tag;
    tree[(p<<1)+1].tag+=tree[p].tag;
    tree[p].tag=0;
}
void change(ll p,ll l,ll r,ll data){
    if(tree[p].l==l&&tree[p].r==r) {
        tree[p].sum+=(r-l+1)*data;tree[p].tag+=data; return;
    }
    push_down(p);
    int m=(tree[p].l+tree[p].r)>>1;
    if(r<=m) change(p<<1,l,r,data);
    else if(l>m) change((p<<1)+1,l,r,data);
         else change(p<<1,l,m,data),change((p<<1)+1,m+1,r,data);
    tree[p].sum=tree[p<<1].sum+tree[(p<<1)+1].sum;
}
ll getsum(ll p,ll l,ll r){
    if(tree[p].l==l&&tree[p].r==r) return tree[p].sum;
    push_down(p);
    int m=(tree[p].l+tree[p].r)>>1;
    if(r<=m) return getsum(p<<1,l,r);
    else if(l>m) return getsum((p<<1)+1,l,r);
         else  return getsum(p<<1,l,m)+getsum((p<<1)+1,m+1,r);
}
int main(){
    n=read();m=read();
    build(1,1,n);
    for(register int i=1;i<=n;i++) { int x=read();change(1,i,i,x); }
    for(register int i=1;i<=m;i++){
        int u=read();
        if(u==1) { int x=read(),y=read(),k=read();change(1,x,y,k); }
        if(u==2) { int x=read(),y=read();printf("%lld\n",getsum(1,x,y));  }
    }
} 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值