您的位置:首页 > 其它

hdu1166 敌兵布阵 线段树单点更新+区间求和

2016-07-06 21:51 316 查看
传送门:hdu1166 敌兵布阵

这个是个中文题目,所以肯定题目的理解不是问题。

解题思路

最基本的线段树,在新增或者删除的时候使用更新函数
updataTree()
来增加营内的数量,查询的时候使用
queryTree
查询出营区间的的认识总和。总而言之是水题。线段树入门题

AC代码

#include<cstdio>
#include<cstring>
#include<set>
#include<stack>
#include<cmath>
#include<cstring>
#include<string>
#include<algorithm>
#include<queue>
#include<cstdlib>
#include<iostream>
#include<map>
using namespace std;
typedef long long LL;  //lld
#define MAXN 400000
int ans;

struct node{
int left;
int right;
int sum;
int mid()
{
return (left+right)>>1;
}
}tree[4*MAXN];

void buildTree(int left,int right,int rt)
{
tree[rt].left = left;
tree[rt].right= right;
if(left == right)
{
scanf("%d",&tree[rt].sum);
return ;
}
int mid = tree[rt].mid();
buildTree(left,mid,rt<<1);
buildTree(mid+1,right,rt<<1|1);
tree[rt].sum = tree[rt<<1].sum + tree[rt<<1|1].sum;
}

void updataTree(int left,int right,int rt,int pos,int sum)
{
if(left == right)
{
tree[rt].sum += sum;
return ;
}
int mid = tree[rt].mid();
if(pos<=mid)
updataTree(left,mid,rt*2,pos,sum);
else
updataTree(mid+1,right,rt*2+1,pos,sum);
tree[rt].sum = tree[rt*2].sum + tree[rt*2+1].sum;
}

void queryTree(int left,int right,int rt,int L,int R)
{
if(L<=left && right<=R)
{
ans+=tree[rt].sum;
return ;
}
int mid = tree[rt].mid();
if(R<=mid)
queryTree(left,mid,rt<<1,L,R);
else if(L>mid)
queryTree(mid+1,right,rt<<1|1,L,R);
else
{
queryTree(left,mid,rt<<1,L,R);
queryTree(mid+1,right,rt<<1|1,L,R);
}
}

int main()
{
int a,b,t,n;
int i,j;
int cnt=1;
char str[20];
scanf("%d",&t);
while(t--)
{
scanf("%d",&n);
buildTree(1,n,1);
printf("Case %d:\n",cnt++);
while(scanf("%s",str))
{
if(str[0] == 'E')
break;
scanf("%d%d",&a,&b);
if(str[0] == 'Q')
{
ans = 0;
queryTree(1,n,1,a,b);
printf("%d\n",ans);
}
if(str[0] == 'A')
updataTree(1,n,1,a,b);
if(str[0] == 'S')
updataTree(1,n,1,a,-b);

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