之前说过这是线段树的裸题,但是当看了http://kenby.iteye.com/blog/962159 这篇题解后我简直震惊了,竟然能如此巧妙地转化为用树状数组来处理,附上部分截图(最好还是进入原网址细细品味):
依照他的思路附上我的代码:
#include<cstdio>
#include<cstring>
#define lowbit(x) ((x)&-(x))
typedef long long LL;
const int maxn= ;
LL org[maxn+]; struct tree{
LL c[maxn+];
void clear() { memset(c,,sizeof(c)); }
LL sum(int x) const {
LL res= ;
while(x){
res+= c[x];
x-= lowbit(x);
}
return res;
}
void add(int x, LL d){
while(x<=maxn){
c[x]+= d;
x+= lowbit(x);
}
}
} d1,d2; inline LL sum(int x) {
return org[x]+(x+)*d1.sum(x)-d2.sum(x);
} int main(){
int n,q,a,b;
LL x,c;
while(~scanf("%d%d",&n,&q)){
memset(org,,sizeof(org));
d1.clear();
d2.clear();
for(int i=; i<=n; ++i){
scanf("%lld",&x);
org[i]= org[i-]+x;
}
while(q--){
getchar();
if(getchar()=='Q'){
scanf("%d%d",&a,&b);
printf("%lld\n",sum(b)-sum(a-));
}
else {
scanf("%d%d%lld",&a,&b,&c);
d1.add(a,c);
d1.add(b+,-c);
d2.add(a,c*a);
d2.add(b+,-c*(b+));
}
}
}
return ;
}
提交后发现比线段树要快一点,再加上代码的精简性,树状数组,果然够强大!