A Simple Problem with Integers POJ - 3468

Problem

给出了一个序列,你需要处理如下两种询问。
“C a b c”表示给[a, b]区间中的值全部增加c (-10000 ≤ c ≤ 10000)。
“Q a b” 询问[a, b]区间中所有值的和。

涉及线段树的区间更新

lazy一下,该PushDown则PushDown即可。注意Update与Query时候的处理。

#include 
#define L(u) (u<<1)
#define R(u) (u<<1|1)
#define ll long long
using namespace std;
const int mx=100000;
struct Tree {
    int lch,rch;
    ll sum,add;
}tree[mx<<2];
int d[mx+10],n,m,x,y,c;
char ops;
void Pushup(int u) {
    tree[u].sum=tree[L(u)].sum+tree[R(u)].sum;
}
void PushDown(int u) {
    if (tree[u].add) {
        tree[L(u)].add += tree[u].add;
        tree[R(u)].add += tree[u].add;
        tree[L(u)].sum += tree[u].add * (tree[L(u)].rch - tree[L(u)].lch + 1);
        tree[R(u)].sum += tree[u].add * (tree[R(u)].rch - tree[R(u)].lch + 1);
        tree[u].add = 0;
    }
}
void Build(int u,int l,int r) {
    tree[u].lch=l;
    tree[u].rch=r;
    tree[u].add=0;
    if (l==r) {
        tree[u].sum=d[l];
        return ;
    }
    int mid=(l+r)>>1;
    Build(L(u),l,mid);
    Build(R(u),mid+1,r);
    Pushup(u);
}
void Update(int u,int l,int r,ll val) {
    if (tree[u].lch==l&&tree[u].rch==r)    {
        tree[u].sum+=val*(r-l+1);
        tree[u].add+=val;
        return;
    }
    if (tree[u].lch==tree[u].rch) return;
    PushDown(u);
    int mid=(tree[u].lch+tree[u].rch)>>1;
    if (l>mid) Update(R(u),l,r,val);
    else if (r<=mid) Update(L(u),l,r,val);
    else {
        Update(L(u),l,mid,val);
        Update(R(u),mid+1,r,val);
    }
    Pushup(u);
}
ll Query(int u,int l,int r) {
    if (l==tree[u].lch&&tree[u].rch==r) return tree[u].sum;
    PushDown(u);
    int mid=(tree[u].lch+tree[u].rch)>>1;
    if (l>mid) return Query(R(u),l,r);
    else if (r<=mid) return Query(L(u),l,r);
    else return Query(L(u),l,mid)+Query(R(u),mid+1,r);
}
int main() {
    scanf("%d%d",&n,&m);
    for (int i=1;i<=n;++i)
        scanf("%d",&d[i]);
    Build(1,1,n);
    while (m--) {
        scanf(" %c",&ops);
        if (ops=='Q') {
            scanf("%d%d",&x,&y);
            printf("%lld\n",Query(1,x,y));
        } else {
            scanf("%d%d%d",&x,&y,&c);
            Update(1,x,y,c);
        }
    }
    return 0;
}

你可能感兴趣的:(数据结构)