HDU 1166--线段树模板题
中文题,不解释。
线段树的模版题,暴力都可以过。。。
思路:
线段树区间求和。
代码:
1 #include<cstdio> 2 #include<iostream> 3 using namespace std; 4 #define lson l,m,(rt<<1) 5 #define rson m+1,r,(rt<<1|1) 6 const int maxn=50010; 7 int sum[maxn<<2]; 8 void Pushup(int rt) 9 { 10 sum[rt]=sum[rt<<1] + sum[rt<<1|1]; 11 } 12 void build(int l,int r,int rt) 13 { 14 if(l==r) 15 { 16 scanf("%d",&sum[rt]); 17 return; 18 } 19 int m= (l+r) >>1; 20 build(lson); 21 build(rson); 22 Pushup(rt); 23 } 24 void update(int pos,int add,int l,int r,int rt) 25 { 26 if(l==r) 27 { 28 sum[rt]+=add; 29 return; 30 } 31 int m=(l+r)>>1; 32 if(pos<=m) update(pos,add,lson); 33 else update(pos,add,rson); 34 Pushup(rt); 35 } 36 int quary(int L,int R,int l,int r,int rt) 37 { 38 if(L<=l&&R>=r) 39 return sum[rt]; 40 int m=(l+r)>>1; 41 int ret=0; 42 if(L<=m) ret+=quary(L,R,lson); 43 if(R>m) ret+=quary(L,R,rson); 44 return ret; 45 } 46 int main() 47 { 48 int t,cas=1,n,a,b; 49 char str[10]; 50 while(~scanf("%d",&t)) 51 { 52 while(t--) 53 { 54 printf("Case %d:\n",cas++); 55 scanf("%d",&n); 56 build(1,n,1); 57 while(1) 58 { 59 scanf("%s",str); 60 if(str[0]=='E') 61 break; 62 scanf("%d %d",&a,&b); 63 if(str[0]=='Q') 64 printf("%d\n",quary(a,b,1,n,1)); 65 else if(str[0]=='S') 66 update(a,-b,1,n,1); 67 else 68 update(a,b,1,n,1); 69 } 70 } 71 } 72 return 0; 73 }
posted on 2013-02-06 21:53 acoderworld 阅读(122) 评论(0) 收藏 举报
【推荐】AI 的力量,开发者的翅膀:欢迎使用 AI 原生开发工具 TRAE
【推荐】2025 HarmonyOS 鸿蒙创新赛正式启动,百万大奖等你挑战
【推荐】博客园的心动:当一群程序员决定开源共建一个真诚相亲平台
· AES 加密模式演进:从 ECB、CBC 到 GCM 的 C# 深度实践
· InnoDB为什么不用跳表,Redis为什么不用B+树?
· 记一次 C# 平台调用中因非托管 union 类型导致的内存访问越界
· [EF Core]聊聊“复合”属性
· 那些被推迟的 C# 14 特性及其背后的故事
· 博客园出海记-开篇:扬帆启航
· 关于布尔类型的变量不要加 is 前缀,被网友们吐槽了,特来完善下
· 30 岁 Java 仍在 “霸榜“:开发者凭什么还在为它熬夜?
· C#中的多级缓存架构设计与实现深度解析
· GPT5写5000行代码,行不行?