您的位置:首页 > 其它

树状数组 模板

2011-03-18 13:17 218 查看
#include<iostream>
#include<string.h>
#include<string>
#include<stdio.h>
using namespace std;
template<class ValueType,int MaxSize>
class TreeArray{
public:
TreeArray():size(MaxSize){}
int low(int n){return n&(-n);}
void clear()
{
memset(ta,0,sizeof(ta));

}
void add(int pos,ValueType v)
{
while(pos<size){
ta[pos]+=v;
pos+=low(pos);//用来的到下一个包含的位置
}
}
ValueType sum(int pos)
{
ValueType v=0;

while(pos>0){
v+=ta[pos];
pos-=low(pos);
}
return v;
}
private:
ValueType ta[MaxSize];
int size;
};
TreeArray<int,1000010> tr;
int main()
{

int v;
int n,m;cin>>n>>m;
for(int i=1;i<=n;i++){
scanf("%d",&v);
tr.add(i,v);
}
string s;
int x,y;
while(m--){
cin>>s;
scanf("%d %d",&x,&y);
if(s=="ADD"){
tr.add(x,y);
}else{
cout<<tr.sum(y)-tr.sum(x-1)<<endl;
}

}

return 0;
}
 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  string