当前位置:网站首页>树状数组模版+例题
树状数组模版+例题
2022-08-05 08:11:00 【9ack!?】
简介
树状数组是一种维护区间和的数据结构,支持单点查询。经过魔改后也可以进行区间修改-单点查询, 区间修改-区间查询。你问为什么没有单点修改, 单点查询?因为数组就可以解决了哈哈。
我这里就不介绍原理了,网上一搜一大把。
基本树状数组
const int maxn = 100;
int a[maxn+5]; // 存放原始数据
int c[maxn+5]; // 存放树状数组
int n; // 存放数据的最大下标
int lowbit(int x) {
return x&(-x);
}
void add(int i, int k) {
while(i <= n) {
c[i] += k;
i += lowbit(i);
}
}
int getsum(int i) {
// 计算从1开始到i(两边都是闭区间)的区间和
int res = 0;
while(i > 0) {
res += c[i];
i -= lowbit(i);
}
}
void init() {
// 创建树的时候调用
for(int i = 1; i <= n; ++i) {
c[i] += a[i];
int j = i + lowbit(i);
if( j <= n) c[j] += c[i];
}
}
// 查询[x, y]
int sum = getsum(y)-getsum(x-1);
区间修改, 单点查询
首先不能直接套用上面的模版,对区间内的每个元素进行单点修改时间复杂度肯定会爆。
思考一下对区间进行修改时的特点,对整个区间进行修改的时候,区间内相邻元素的差值是不变的,所以我们可以用树状数组维护原数组的差分数组,修改的时候只需要对区间的两个端点修改即可。查询某个点的值时,求出差分数组的前缀和即可。
// 这里的函数直接套用上面的模版即可
// [x, y]区间加上k
for(int i = 1; i <= n; ++i) {
// 读入数据
scanf("%d", &a[i]);
update(i, a[i]-a[i-1]);
}
// [x, y]区间加上k
update(x, k);
update(y+1, -k);
int sum = getsum(i); // 这里的getsum变成了对差分数组的前i个元素进行求和, 于是得到的是a[i]
区间修改, 区间查询
这个就更玄学了,这个问题完全可以用线段树来解决,而且明显树状数组能维护的信息不如线段树多。但是线段树的常数要比线段树小,所以在某些条件下还是能解决一些问题的 (就比如下面的例题)
实际代码模版也差不多,但是运用了更加神奇的方法
// 需要维护两个树状数组
const int maxn;
int n, m;
int a[maxn];
int sum1[maxn]; // (D[1] + D[2] + ... D[n]), D是差分数组
int sum2[maxn]; // (1*D[1] + 2*D[2] + .. + n*D[n])
void update(int i, int k) {
int x = i;
while(i <= n) {
sum1[i] += k;
sum2[i] += k*(x-1);
i += lowbit(i);
}
}
int getsum(int i) {
int res = 0, x = i;
while(i > 0) {
res += x*sum1[i] - sum2[i];
i -= lowbit(i);
}
return res;
}
// 读入数据
for(int i = 1; i <= n; ++i) {
scanf("%d", &a[i]);
update(i, a[i]-a[i-1]);
}
// [x, y]区间加上k
update(x, k);
update(y+1, -k);
// 求[x, y]区间和
int sum = getsum(y) - getsum(x-1);
//连这一篇都要限流...
边栏推荐
猜你喜欢
php向mysql写入数据失败
Fiddler工具讲解
php向mysql写入数据失败
SVG大鱼吃小鱼动画js特效
爬虫之验证码
MongoDB 语法大全
uniapp时间组件封装年-月-日-时-分-秒
How to make pictures clear in ps, self-study ps software photoshop2022, simple and fast use ps to make photos clearer and more textured
Use of thread pool (combined with Future/Callable)
JVM运行流程,运行时数据区,类加载,垃圾回收,JMM解析
随机推荐
高效使用数码相机的诀窍
【每日一题】1403. 非递增顺序的最小子序列
unity 头发的渲染
Basic introduction of stack and queue and C language implementation of functions such as creation, destruction, entry and exit, counting the number of elements, viewing elements, etc., as well as stac
【 a daily topic 】 1403. The increasing order of the sequence, boy
在原有数据库基础上执行sql文件有则跳过没有则添加如何实现?
Chapter3、色调映射
真正爱你的女人是这样的
iptables实现网络限制下ntp自定义端口同步时间
Chapter 12 Bayesian Networks
路由----router
漂亮MM和普通MM的区别
v-if/v-else根据计算判断是否显示
链表专项之环形链表
在ASP控制数字及字母输入
【结构体内功修炼】结构体内存对齐(一)
原型&原型链
Codeforce 8.1-8.7做题记录
Qt编写自定义控件:文字聚光灯效果之一
Controlling number and letter input in ASP