单点修改+区间查询
#include<cstdio>
#include<cstring>
const int N=1e5+7;
inline int lowbit(int x){
return x&(-x);
}
inline int read(){
int ans=0;char t=getchar();int f=1;
while(t<'0'||t>'9') f=(t=='-'?-1:1),t=getchar();
while(t>='0'&&t<='9') ans=ans*10+t-'0',t=getchar();
return ans*f;
}
int c[N];
int n;
inline void modify(int x,int num)
{
for( ;x<=n;x+=lowbit(x))
c[x]+=num;
}
inline int query(int x)
{
int sum=0;
for( ;x>=1;x-=lowbit(x))
sum+=c[x];
return sum;
}
int main()
{
n=read();
int u,v;
for(int i=1;i<=n;i++)u=read(),modify(i,u);
int m=read();
int opt;
for(int i=1;i<=m;i++)
{
opt=read();
if(opt==1) u=read(),v=read(),modify(u,v);
else u=read(),v=read(),printf("%d\n",query(v)-query(u-1));
}
return 0;
}
区间修改+单点查询(差分)
#include<cstdio>
#include<cstring>
const int N=1e5+7;
inline int lowbit(int x){
return x&(-x);
}
inline int read(){
int ans=0;char t=getchar();int f=1;
while(t<'0'||t>'9') f=(t=='-'?-1:1),t=getchar();
while(t>='0'&&t<='9') ans=ans*10+t-'0',t=getchar();
return ans*f;
}
int delta[N];int c[N];
int n;
inline void modify(int x,int num)
{
for( ;x<=n;x+=lowbit(x))
c[x]+=num;
}
inline int query(int x)
{
int sum=0;
for( ;x>=1;x-=lowbit(x))
sum+=c[x];
return sum;
}
int main()
{
n=read();
int pre=0,u,v,q;
for(int i=1;i<=n;i++){
u=read(),delta[i]=u-pre;pre=u;
modify(i,delta[i]);
}
int m=read();
int opt;
for(int i=1;i<=m;i++)
{
opt=read();
if(opt==1)
{
u=read(),v=read(),q=read();
modify(u,q);
modify(v+1,-q);
}
else
{
u=read();
printf("%d\n",query(u));
}
}
return 0;
}
区间修改+区间查询
#include<cstdio>
#include<cstring>
const int N=2*1e5+7;
inline int lowbit(int x){
return x&(-x);
}
inline long long read(){
long long ans=0;char t=getchar();int f=1;
while(t<'0'||t>'9') f=(t=='-'?-1:1),t=getchar();
while(t>='0'&&t<='9') ans=ans*10+t-'0',t=getchar();
return ans*f;
}
long long c[N],c2[N];
long long n;
inline void modify(int x,long long num)
{
for( ;x<=n;x+=lowbit(x))
c[x]+=num;
}
inline void modify2(int x,long long num)
{
for( ;x<=n;x+=lowbit(x))
c2[x]+=num;
}
inline long long int query(int x)
{
long long int sum=0;
for( ;x>=1;x-=lowbit(x))
sum+=c[x];
return sum;
}
inline long long int query2(int x)
{
long long int sum=0;
for( ;x>=1;x-=lowbit(x))
sum+=c2[x];
return sum;
}
int main()
{
n=read();
long long pre=0,u,v,q,delta;
for(int i=1;i<=n;i++){
u=read(),delta=u-pre;pre=u;
modify(i,delta);
modify2(i,(i-1)*delta);
}
long long m=read();
int opt;
for(int i=1;i<=m;i++)
{
opt=read();
if(opt==1)
{
u=read(),v=read(),q=read();
modify(u,q); modify(v+1,-q);
modify2(u,(u-1)*q);modify2(v+1,-v*q);
}
else
{
u=read(),v=read();
printf("%lld\n", ( v*query(v)-query2(v) )-( (u-1)*query(u-1)-query2(u-1) ) );
}
}
return 0;
}