HDU 1166.敌兵布阵-完全版线段树(单点增减、区间求和)

生活艰辛,且行且珍惜。

先水一篇博客再去补题,要不然又忘记写博客了。

计划系统的刷一遍线段树专题,自己给自己找虐(自作孽不可活),从基础的到后面的,所有的都挂了题,刷题不,大兄弟?

线段树可真有意思,先写5道题的题解。

数据结构,好好刷专题,真的要好好刷专题,因为害怕队友嫌我太菜不要我了(好想哭啊)

少瓜皮,正经一点,队友就不嫌弃我了。。。

正题:

刷线段树主要参考模板是这两篇博客再加自己的习惯:

传送门:1.完全版线段树2.线段树详解

HDU1166.敌兵布阵

基础的单点增减、区间求和操作,直接模板就可以

代码:

 //A
#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<algorithm>
#include<cstdlib>
#include<queue>
#include<stack>
using namespace std;
typedef long long ll;
const int inf=0x3f3f3f3f;
const double eps=1e-;
const int maxn=*1e5+;
#define lson l,m,rt<<1
#define rson m+1,r,rt<<1|1
int sum[maxn<<],MAX[maxn<<],col[maxn<<]; void PushUp(int rt){
sum[rt]=sum[rt<<]+sum[rt<<|];
//MAX[rt]=max(MAX[rt<<1],MAX[rt<<1|1]);
} void build(int l,int r,int rt){
if(l==r){
scanf("%d",&sum[rt]);
//scanf("%d",&MAX[rt]);
return ;
}
int m=(l+r)>>;
build(lson);
build(rson);
PushUp(rt);
} //单点增减
void update(int p,int add,int l,int r,int rt){
if(l==r){
sum[rt]+=add;
return ;
}
int m=(l+r)>>;
if(p<=m)update(p,add,lson);
else update(p,add,rson);
PushUp(rt);
}
/*
//单点替换
void update(int p,int sc,int l,int r,int rt){
if(l==r){
MAX[rt]=sc;
return ;
}
int m=(l+r)>>1;
if(p<=m)update(p,sc,lson);
else update(p,sc,rson);
PushUp(rt);
}
*/
//区间求和
int query(int L,int R,int l,int r,int rt){
if(L<=l&&r<=R){
return sum[rt];
}
int m=(l+r)>>;
int ret=;
if(L<=m)ret+=query(L,R,lson);
if(R>m) ret+=query(L,R,rson);
return ret;
} /*
//区间最值
int query(int L,int R,int l,int r,int rt){
if(L<=l&&r<=R){
return MAX[rt];
}
int m=(l+r)>>1;
int ret=0;
if(L<=m)ret=max(ret,query(L,R,lson));
if(R>m) ret=max(ret,query(L,R,rson));
return ret;
}
*/ int main(){
int t,n;
scanf("%d",&t);
for(int i=;i<=t;i++){
scanf("%d",&n);
build(,n,);
char s[];int a,b;
printf("Case %d:\n",i);
while(~scanf("%s",s)){
if(s[]=='E')break;
else{
scanf("%d%d",&a,&b);
if(s[]=='Q')printf("%d\n",query(a,b,,n,));
else if(s[]=='A')update(a,b,,n,);
else update(a,-b,,n,);
}
}
}
return ;
}
上一篇:前端面试题总结:HTML5,JS,CSS3,兼容性。


下一篇:HDU 1754 I Hate It(线段树之单点更新,区间最值)