1. 程式人生 > >ACM-ICPC 2018 徐州賽區網路預賽 H. Ryuji doesn't want to study —— 線段樹lazy標記區間修改

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.

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<bits/stdc++.h>
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<l)
        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;
        }
    }
}