模板_SEG_TREE

#include<bits/stdc++.h>
#define maxn 500005
#define int long long
using namespace std;
inline int read()
{
    char x = getchar();
    int lin = 0, f = 1;
    while(x < '0' || x > '9')
    {
        if(x == '-') f = -1;
        x = getchar();
    }
    while(x >= '0' && x <= '9')
    {
        lin = (lin << 1) + (lin << 3) + x - '0';
        x = getchar();
    }
    return lin * f;
}
#define PII pair<int,int>
#define fir first
#define sec second
#define ma(a,b) make_pair(a,b)
#define db double
#define inf 123123123
int n,m,v[maxn],x,y,ty,val;
struct tree{
    int l,r,add,val;
}tr[maxn];
#define le tr[k].l
#define re tr[k].r
#define upd tr[k].val = tr[k << 1].val + tr[k << 1 | 1].val;
void pbd(int k,int val)
{
    tr[k].val = tr[k].val + (re - le + 1) * val;
    tr[k].add = tr[k].add + val;
}
void pb(int k)
{
    if(tr[k].add)
    {
        pbd(k << 1,tr[k].add);
        pbd(k << 1 | 1,tr[k].add);
        tr[k].add = 0;
    }
}
void update(int l,int r,int k,int val)
{
    if(l <= le && re <= r) { pbd(k,val); return; }
    pb(k);
    int mid = le + re >> 1;
    if(l <= mid) update(l,r,k << 1,val);
    if(r > mid) update(l,r,k << 1 | 1,val);
    upd;
}
int query(int l,int r,int k)
{
    if(l <= le && re <= r) return tr[k].val;
    pb(k);
    int ans = 0,mid = le + re >> 1;
    if(l <= mid) ans = ans + query(l,r,k << 1);
    if(r > mid) ans = ans + query(l,r,k << 1 | 1);
    return ans;
}
void build(int l,int r,int k)
{
    le = l; re = r;
    if(l == r) { tr[k].val = v[l]; return; }
    int mid = l + r >> 1;
    build(l,mid,k << 1); build(mid + 1,r,k << 1 | 1);
    upd;
}
signed main(){
    n = read(); m = read();
    for(int i = 1; i <= n; i++) v[i] = read();
    build(1,n,1);
    for(int i = 1; i <= m; i++)
    {
        ty = read(); x = read(); y = read();
        if(ty == 1) { val = read(); update(x,y,1,val); }
        else printf("%lld\n",query(x,y,1));
    }
}

 

posted @ 2018-11-07 14:32  cc123321  阅读(229)  评论(0编辑  收藏  举报