博客目录
传送门
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.
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标志即可。
#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 || Rreturn 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;
}
}
}