http://codevs.cn/problem/1082/
#include <algorithm>
#include <stdio.h>
#include <cstring>
using namespace std;
const int maxn = 1e5+1;
int C[maxn];
int C2[maxn];
int p[maxn];
int n;
int lowbit(int x){
return (-x)&x;
}
void update(int i,int num){
while(i <= n){
C[i]+=num;
i+=lowbit(i);
}
}
int sigma(int c[maxn],int i){
int s = 0;
for(in i = n; i > 0 ; i-=lowbit(i))
s+=c[i];
return s;
}
int main(){
memset(C,0,sizeof C);
memset(p,0,sizeof p);
cin>>n;
for(int i = 1; i <= n;i++ )
{
cin>>p[i];
update(i,p[i]-p[i-1]);
}
int w;
cin>>w;
if(w == 1)
{
int a,b;
int x;
cin>>a>>b>>x;
update(a,x);
update(b+1,-x);
}
else{
int a,b;
cin>>a>>b;
for(int i = 1; i <= n;i++)
C2[i]=C[i]*(i-1);
a--;
int sum1 = b*sigma(C,b)-sigma(C2,b);
int sum2 = a*sigma(C,a)-sigma(C,a);
cout<<sum1 - sum2<<endl;
}
return 0;
}
本文介绍了一种使用差分数组和前缀和技巧实现区间更新和查询的算法。该算法适用于处理一系列数值更新操作,并能高效地计算指定区间内元素的累计值。文章通过一个具体的代码示例展示了如何初始化数组、进行区间更新以及执行区间查询。
949

被折叠的 条评论
为什么被折叠?



