您的位置:首页 > 其它

hdu1166 线段树,点修改,区间求和

2013-07-29 14:03 239 查看
链接:http://acm.hdu.edu.cn/showproblem.php?pid=1166

题意:中文的。求若干个区间中工人的个数。

思路:简单线段树,点修改。只更新叶子节点,然后把信息用PushUP(int r)这个函数更新上来。

#include<cmath>
#include<cmath>
#include<algorithm>
#include<iostream>
#include<cstdio>
using namespace std;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
const int maxn=55555;//最大区间长度
int sum[maxn<<2];//节点数组,4倍长度
void PushUP(int rt)
{
sum[rt]=sum[rt<<1]+sum[rt<<1|1];
}
void build(int l,int r,int rt)
{
if(l==r)
{
scanf("%d",&sum[rt]);
return;
}
int m=(l+r)>>1;
build(lson);
build(rson);
PushUP(rt);
}
void update(int p,int add,int l,int r,int rt)
{//对p进行更新操作,加上add,l,r表示操作范围,rt表示当前节点
if(l==r)
{
sum[rt]+=add;
return;
}
int m=(l+r)>>1;
if(p<=m) update(p,add,lson);
else update(p,add,rson);
PushUP(rt);
}
int query(int L,int R,int l,int r,int rt)
{//[L,R]要查询的区间,[l,r]当前节点所在区间
if(L<=l && r<=R)
return sum[rt];
int m=(l+r)>>1;
int ret=0;
if(L<=m) ret+=query(L,R,lson);
if(R>m) ret+=query(L,R,rson);
return ret;
}
int main()
{
int t,n,ca=1;
scanf("%d",&t);
while(t--)
{
printf("Case %d:\n",ca++);
scanf("%d",&n);
build(1,n,1);
char op[10];
while(scanf("%s",op))
{
if(op[0]=='E') break;
int a,b;
scanf("%d%d",&a,&b);
if(op[0]=='Q') printf("%d\n",query(a,b,1,n,1));
else if(op[0]=='S') update(a,-b,1,n,1);
else update(a,b,1,n,1);
}
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: