您的位置:首页 > 其它

HDU1166敌兵布阵-线段树求和

2016-10-10 15:40 302 查看
HDU1166敌兵布阵-线段树求和

#include<stdio.h>
#include<iostream>
#include<string.h>
#include<string>
using namespace std;
const int maxn = 200005*2;
long long n,dat[2*maxn-1];
void init(int n_)
{
n = 1;
while(n<n_)n*=2;
for(int i = 0 ;i < 2*n-1;i++)
dat[i]= 0;
}
void update(int k,int a)
{
k += n-1;
dat[k] += a;
while(k>0)
{
k = (k-1)/2;
dat[k]+=a;
}
}
int query(int a, int b,int k,int l ,int r)
//查询用 query(a,b,0,0,n)·查询[a,b)
{
if(r<=a||b<=l){return 0;}
if(a<=l&&r<=b)return dat[k];
else
{
int vl = query(a,b,k*2+1,l,(l+r)/2);
int vr = query(a,b,k*2+2,(l+r)/2,r);
return vl+vr;
}
}
int main()
{
int m,a;
char op[10];
cin>>m;
for(int k = 1; k <= m ; k++)
{
cout<<"Case "<<k<<":"<<endl;
scanf("%d",&n);
init(n);
for(int i = 0 ; i < n; i++)
{
scanf("%d",&a);
update(i,a);
}
int op1,op2;
scanf("%s",op);
while(strcmp(op,"End"))
{
scanf("%d %d",&op1,&op2);
if(strcmp(op,"Query")==0)
{
printf("%d\n",query(op1-1,op2,0,0,n));
}
else if(strcmp(op,"Add")==0)
{
update(op1-1,op2);
}
else if(strcmp(op,"Sub")==0)
{
update(op1-1,-op2);
}
getchar();
scanf("%s",op);
}
}
return 0;
}

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