Link:http://acm.hdu.edu.cn/showproblem.php?pid=1166
#include <bits/stdc++.h>
using namespace std;
const int N = 5e4+5;
char s[10];
int tree[N],n;
void add(int x,int num){
while(x<=n){
tree[x]+=num;
x += x&(-x);
}
}
int getpre(int x){
int ans = 0;
while(x){
ans+=tree[x];
x -= x&(-x);
}
return ans;
}
int query(int x,int y){
return getpre(y)-getpre(x-1);
}
int main(){
int T,a;
scanf("%d",&T);
for(int cas=1; cas<=T; cas++){
memset(tree,0,sizeof(tree));
scanf("%d",&n);
for(int i = 1; i <= n; i++)
{
scanf("%d",&a);
add(i,a);
}
printf("Case %d:\n",cas);
int x,y;
while(~scanf("%s",s)){
if(strcmp(s,"End")==0)
break;
scanf("%d%d",&x,&y);
if(strcmp(s,"Add")==0)
add(x,y);
else if(strcmp(s,"Sub")==0)
add(x,-y);
else
printf("%d\n",query(x,y));
}
}
return 0;
}
本文提供了一道来自HDU在线评测系统的编程题(编号1166)的解答思路及实现代码。该解决方案使用了树状数组(Binary Indexed Tree, BIT)来高效地处理区间查询与更新操作。
3850

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



