树状数组板子题(访问与修改)
题目链接
http://acm.hdu.edu.cn/showproblem.php?pid=1166
AC代码
#include<bits/stdc++.h>
using namespace std;
const int N=5e4+10;
int c[N],a[N];
int n;
int lowbit(int x){
return x&(-x);
}
int getsum(int x){
int ans=0;
while(x>0){
ans+=c[x];
x-=lowbit(x);
}
return ans;
}
void update(int x,int num){
while(x<=n){
c[x]+=num;
x+=lowbit(x);
}
}
int main(){
int t;
cin>>t;
for(int k=1;k<=t;k++){
string cmd;
cin>>n;
//input array a
for(int i=1;i<=n;i++)
cin>>a[i];
//init array c
memset(c,0,sizeof c);
for(int i=1;i<=n;i++)
update(i,a[i]);
printf("Case %d:\n",k);
while(1){
//input command
cin>>cmd;
if(cmd=="End") break;
else if(cmd=="Add"){
int x,add;
cin>>x>>add;
update(x,add);
}
else if(cmd=="Sub"){
int x,sub;
cin>>x>>sub;
update(x,-sub);
}
else if(cmd=="Query"){
int x,y;
cin>>x>>y;
cout<<getsum(y)-getsum(x-1)<<endl;
}
}
}
} 总结
比较简单,只要记住了三个函数,这种基础题就比较容易了。
当时做的时候忘记了cin>>string能不能接收空格了,答案是不能。
若想接收空格,getline(cin,str);getline函数。
再就是string类型能直接进行字符串判等操作。
就注意这几点就ok,实现真的很简单。

