我是靠谱客的博主 糊涂电脑,这篇文章主要介绍HDU-1166-敌兵布阵(树状数组,附解释),现在分享给大家,希望可以做个参考。

HDU-1166-敌兵布阵(树状数组)

http://acm.hdu.edu.cn/showproblem.php?pid=1166


初学树状数组,,  
题目大意:更新点查区间,,
简单介绍一下树状数组,看下图。


c1 = a1

c3 = a3

c4 = a1 + a2 + a3 + a4

c5 = a5

c6 = a5 + a6

c7 = a7

c8 = a1 + a2 + a3 + a4 + a5 + a6 + a7 + a8

c9=a9
c10=a9+a10


对于序列a,我们设一个数组C定义C[i] = a[i – 2^k + 1] + … + a[i],k为i在二进制下末尾0的个数

求2^k

求x在二进制下末尾0的个数(第一个一出现的位置)

复制代码
1
2
3
4
5
int lowbit(int x) { return x&(x^(x-1)); }
将a[p]的值加上一个值x

复制代码
1
2
3
4
5
6
7
8
9
void update(int p,int x) { while(p<=n) { c[p]+=x; p+=lowbit(p); } }
求前p项和

复制代码
1
2
3
4
5
6
7
8
9
10
11
int sum(int p) { int sum=0; while(p>0) { sum+=c[p]; p-=lowbit(p); } return sum; }
题目代码:

复制代码
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include<cstdio> #include<cstring> #define lowbit(x) (x&(x^(x-1))) #define maxn 50010 using namespace std; int c[maxn]; int n; void update(int p,int x)///给 a[p] 加上 x { while(p<=n){ c[p]+=x; p+=lowbit(p); } } int sum(int p) ///求前P项的和 { int sum=0; while(p>0){ sum+=c[p]; p-=lowbit(p); } return sum; } int main() { int T,t=0; char str[10]; scanf("%d",&T); while(T--) { int x,y; scanf("%d",&n); memset(c,0,sizeof(c)); for(int i=1;i<=n;i++){ scanf("%d",&x); update(i,x); } printf("Case %d:n",++t); while(scanf("%s",str)&&str[0]!='E'){ scanf("%d %d",&x,&y); if(str[0]=='A') update(x,y); else if(str[0]=='S') update(x,-y); else if(str[0]=='Q'){ printf("%dn",sum(y)-sum(x-1)); } } } return 0; }

参考文章:http://blog.csdn.net/cambridgeacm/article/details/7771782


最后

以上就是糊涂电脑最近收集整理的关于HDU-1166-敌兵布阵(树状数组,附解释)的全部内容,更多相关HDU-1166-敌兵布阵(树状数组内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(62)

评论列表共有 0 条评论

立即
投稿
返回
顶部