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  阅读(121)  评论(0)    收藏  举报

编辑推荐:
· 没有调度器的协程不是好协程,零基础深入浅出 C++20 协程
· 别做抢活的导演:代码中的抽象层次原则
· 从 Redis 客户端超时到 .NET 线程池挑战
· C23和C++26的#embed嵌入资源指南
· 「EF Core」框架是如何识别实体类的属性和主键的
阅读排行:
· 阿里巴巴为什么禁止超过3张表join?
· 博客园众包线下沙龙第1期:云栖开发者基地,共建技术新天地
· 让 AI 帮我部署网站,太方便了!
· 别做抢活的导演:代码中的抽象层次原则
· .NET周刊【7月第1期 2025-07-06】
< 2025年7月 >
29 30 1 2 3 4 5
6 7 8 9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30 31 1 2
3 4 5 6 7 8 9

导航

统计

点击右上角即可分享
微信分享提示