ACM-ICPC 2018 徐州赛区网络预赛 H. Ryuji doesn't want to study —— 线段树lazy标记区间修改

博客目录

原题

 

传送门

  •  1000ms
  •  262144K

Ryuji is not a good student, and he doesn't want to study. But there are n books he should learn, each book has its knowledge a[i]a[i].

Unfortunately, the longer he learns, the fewer he gets.

Now Ryuji has qq questions, you should answer him:

11. If the question type is 11, you should answer how much knowledge he will get after he reads books [ ll, rr ].

22. If the question type is 22, Ryuji will change the ith book's knowledge to a new value.

ACM-ICPC 2018 徐州赛区网络预赛 H. Ryuji doesn't want to study —— 线段树lazy标记区间修改_第1张图片

Output

For each question, output one line with one integer represent the answer.

样例输入复制

5 3
1 2 3 4 5
1 1 3
2 5 0
1 4 5

样例输出复制

10
8

思路

其实这个可以分解为len个前缀和。设sum(l,r)表示l到r的和,则上式等于:

sum(l,l)+sum(l,l+1)+sum(l,l+2)+...+sum(l,r)

=sum(1,l)+sum(1,l+1)+sum(1,l+2)+...+sum(1,r)-(r-l+1)*sum(1,l-1)

则转化为求前缀和的区间和。然后对单点修改,相当于对要修改的位置i到n所有的前缀和都加增量。

也就转化为线段树查询区间和,区间修改。

区间修改用lazy标志即可。

AC代码

#include
using namespace std;
typedef long long ll;
#define lson l , m , rt << 1 
#define rson m + 1 , r , rt << 1 | 1
const int maxn = 1e5+10;
ll tree[maxn<<3];
ll lz[maxn<<3];
int ip;
#define lcvalue(rt) (lz[rt<<1]*(m-l+1)+tree[rt<<1])
#define rcvalue(rt) (lz[rt<<1|1]*(r-m)+tree[rt<<1|1])
#define PushUP(rt) tree[rt] = lcvalue(rt)+ rcvalue(rt)
int n,q;
ll fo[maxn];
void build(ll l,ll r,ll rt) {
    if (l == r) {
       tree[rt]=fo[ip++];
       return ;
    }
    ll m = (l + r) >> 1;
    build(lson);
    build(rson);
    PushUP(rt);
}
ll query(ll L,ll R,ll l,ll r,ll rt,ll z){
    lz[rt]+=z;
    if(L>r || R         return 0;
    if (L <= l && r <= R) {
        return tree[rt]+lz[rt]*(r-l+1);
    }
    ll m = (l + r) >> 1;
    ll ret = 0;
       ret += query(L , R , lson,lz[rt]);
    ret += query(L , R , rson,lz[rt]);
    tree[rt]+=lz[rt]*(r-l+1);
    lz[rt]=0;
    return ret;
}
void update(int L,int R,ll add,ll l,ll r,ll rt) {
    if (l == r) {
        tree[rt] += add;
        return ;
    }
    if (L <= l && r <= R) {
        lz[rt]+=add;
        return;
    }
    ll m = (l + r) >> 1;
    if (L <= m) update(L,R, add , lson);
    if(R>m)    update(L,R, add , rson);
    PushUP(rt);
}
int co[maxn];
signed main(){
    cin>>n>>q;
    for(int i=1;i<=n;i++){
        scanf("%d",co+i);
        fo[i]=co[i]+fo[i-1];
    }
    ip=1;
    build(1,n,1);
    int l,r,len,sum,v;
    for(int i=1;i<=q;i++){
        scanf("%d",&l);
        if(l==1){//query
            scanf("%d%d",&l,&r);
            len=r-l+1;
            printf("%lld\n",query(l,r,1,n,1,0)-len*query(l-1,l-1,1,n,1,0));
        }
        else{
            scanf("%d%d",&l,&v);
            update(l,n,v-co[l],1,n,1);
            co[l]=v;
        }
    }
}
 

你可能感兴趣的:(线段树)