【初识——树状数组】 区间求和
2015-11-27 22:05
337 查看
说树状数组其实是一个索引表,但是是一个特殊的,树状的索引表,它利用了二进制的一些特性。
就区间求和的要求来说:
首先我们用a[]数组来存储原始数据。然后在a[]之上构造c[]数组来作为树状数组。
如图
View Code
就区间求和的要求来说:
首先我们用a[]数组来存储原始数据。然后在a[]之上构造c[]数组来作为树状数组。
如图
#include <cstdio> #include <cmath> #include <cstring> #include <algorithm> using namespace std; const int N = 50005; int t, n; int a ; int c ; char s[10]; int x, y; int lowbit(int x) { return x&(-x); } void Add(int x, int y) { a[x] += y; while(x <= n) { c[x] += y; x += lowbit(x); } } int Sum(int x) { int rt = 0; while(x > 0) { rt += c[x]; x -= lowbit(x); } return rt; } int Summ(int l, int r) { int rt = 0; while(r >= l) { if(r-lowbit(r) < l) { rt += a[r]; r -= 1; } else { rt += c[r]; r -= lowbit(r); } } return rt; } void Query(int a, int b) { printf("%d\n", Sum(b)-Sum(a-1)); //printf("%d\n", Summ(a, b)); } int main() { //freopen("test.in", "r", stdin); scanf("%d", &t); for(int tm = 1; tm <= t; tm++) { scanf("%d", &n); memset(c, 0, sizeof(c)); memset(a, 0, sizeof(a)); int y; for(int i = 1; i <= n; i++) { scanf("%d", &y); Add(i, y); } printf("Case %d:\n", tm); scanf("%s", s); while(s[0] != 'E') { scanf("%d%d", &x, &y); if(s[0] == 'A') Add(x, y); if(s[0] == 'Q') Query(x, y); if(s[0] == 'S') Add(x, -y); scanf("%s", s); } } }
View Code
相关文章推荐
- [python]错误检测及异常处理try-except
- 网络多线程-GCD的基本使用
- swift 中字符串比较
- 网络多线程-NSThread实现线程间通信
- Linux命令-组合命令
- 远程debug 查不到变量的值
- 很多人很想知道怎么扫一扫二维码就能打开网站,就能添加联系人,就能链接wifi,今天做个demo(续集)
- JDBCl类的步骤
- Lint_Code_最多有多少个点在一条直线上
- 特征提取初步了解
- 网络多线程-线程的安全
- java 学习笔记
- 闪存芯片封装技术介绍——TSOP、FBGA、LGA
- [原][树莓派] - 内核模块编译--续
- Caffe + Ubuntu 14.04 64bit + CUDA 6.5 配置说明2
- 第二个Sprint冲刺第五天
- Linux命令——任务控制
- 网络多线程-线程的状态
- 安卓Genymotion模拟器安装与配置在Eclipse
- Python-学习笔记(一)——环境配置+IDE搭建(WingIDE)