码迷,mamicode.com
首页 > 其他好文 > 详细

【线段树(单点修改,区间求和)】HDU1166 - 敌军布阵

时间:2015-09-28 23:46:08      阅读:228      评论:0      收藏:0      [点我收藏+]

标签:

hdu1166 敌兵布阵,单点修改,区间求和。

【ATTENTION】MAXN要开成节点数的4倍,开得不够会提示TLE。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #define lson l,m,root<<1
 5 #define rson m+1,r,root<<1|1
 6 using namespace std;
 7 const int MAXN=50000*4+500;
 8 int n;
 9 int sum[MAXN];
10 
11 void pushUP(int root)
12 {
13     sum[root]=sum[root<<1]+sum[root<<1|1];
14 }
15 
16 void build(int l,int r,int root)
17 {
18     if (l==r)
19     {
20         scanf("%d",&sum[root]);
21         return;
22     }
23     int m=(l+r)>>1;
24      build(lson);
25     build(rson);
26     pushUP(root);
27 }
28 
29 void update(int p,int delta,int l,int r,int root)
30 {
31     if (l==r)
32     {
33         sum[root]+=delta;
34         return;
35     }
36     int m=(l+r)>>1;
37     if (p<=m) update(p,delta,lson);
38     if (p>m) update(p,delta,rson);
39     pushUP(root);
40 }
41 
42 int query(int L,int R,int l,int r,int root)
43 {
44     int result=0;
45     if (l>=L && r<=R)
46     {
47         return sum[root];
48     }
49     int m=(l+r)>>1;
50     if (L<=m) result+=query(L,R,lson);
51     if (R>m) result+=query(L,R,rson);
52     return result;
53 }
54 
55 int main()
56 {
57     int t;
58     scanf("%d",&t);
59     for (int kase=0;kase<t;kase++)
60     {
61         cout<<"Case "<<kase+1<<":"<<endl;
62         scanf("%d",&n);
63         build(1,n,1);
64         char s[6];
65         while (scanf("%s",s))
66         {
67             if (s[0]==E) break;
68             int a,b;
69             scanf("%d%d",&a,&b);
70             if (s[0]==A) update(a,b,1,n,1);
71             if (s[0]==S) update(a,-b,1,n,1);
72             if (s[0]==Q) cout<<query(a,b,1,n,1)<<endl;
73         } 
74     }
75     return 0;
76 }

 

【线段树(单点修改,区间求和)】HDU1166 - 敌军布阵

标签:

原文地址:http://www.cnblogs.com/iiyiyi/p/4845222.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!