您的位置:首页 > 其它

【线段树(单点修改,区间求和)】HDU1166 - 敌军布阵

2015-09-28 23:00 330 查看
hdu1166 敌兵布阵,单点修改,区间求和。

【ATTENTION】MAXN要开成节点数的4倍,开得不够会提示TLE。

#include<iostream>
#include<cstdio>
#include<cstring>
#define lson l,m,root<<1
#define rson m+1,r,root<<1|1
using namespace std;
const int MAXN=50000*4+500;
int n;
int sum[MAXN];

void pushUP(int root)
{
sum[root]=sum[root<<1]+sum[root<<1|1];
}

void build(int l,int r,int root)
{
if (l==r)
{
scanf("%d",&sum[root]);
return;
}
int m=(l+r)>>1;
build(lson);
build(rson);
pushUP(root);
}

void update(int p,int delta,int l,int r,int root)
{
if (l==r)
{
sum[root]+=delta;
return;
}
int m=(l+r)>>1;
if (p<=m) update(p,delta,lson);
if (p>m) update(p,delta,rson);
pushUP(root);
}

int query(int L,int R,int l,int r,int root)
{
int result=0;
if (l>=L && r<=R)
{
return sum[root];
}
int m=(l+r)>>1;
if (L<=m) result+=query(L,R,lson);
if (R>m) result+=query(L,R,rson);
return result;
}

int main()
{
int t;
scanf("%d",&t);
for (int kase=0;kase<t;kase++)
{
cout<<"Case "<<kase+1<<":"<<endl;
scanf("%d",&n);
build(1,n,1);
char s[6];
while (scanf("%s",s))
{
if (s[0]=='E') break;
int a,b;
scanf("%d%d",&a,&b);
if (s[0]=='A') update(a,b,1,n,1);
if (s[0]=='S') update(a,-b,1,n,1);
if (s[0]=='Q') cout<<query(a,b,1,n,1)<<endl;
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: