当前位置:网站首页>树状数组的基本用法
树状数组的基本用法
2022-07-30 05:55:00 【四舍五入两米高的小晨】
1.树状数组的用处:
- 在数组的某个位置上加上一个数
- 求某一个前缀和
- 最主要的是这些都是可以动态求出
2.树状数组的构成
树状数组中的每个元素由一段区间构成,例如TR[i]是由(x-lowbit(x),x]构成。(注意左开右闭)
3.写树状数组的核心代码
int lowbit(int x)
{
return x&-x;
}
//第x个数加上v
int add(int x,int v)
{
//从当前位置开始加,每个间隔是lowbit(i),每次找到它上面的那个数,直到n
for(int i=x;i<=n;i+=lowbit(i))
tr[i]+=v;
}
//返回x的前缀和
int query(int x)
{
int res=0;
//从当前位置开始累加,每个间隔是lowbit(i),一直减到i==0停止
for(int i=x;i;i-=lowbit(i)) res+=tr[i];
return res;
}
4.例题:
代码:
// 时间:2022.07.26 18点07分
// 算法:树状数组
#include<iostream>
using namespace std;
const int N=100010;
int a[N],tr[N];
int n,m;
int lowbit(int x)
{
return x & -x;
}
void add(int x,int v)
{
for(int i=x;i<=n;i+=lowbit(i)) tr[i]+=v;
}
int query(int x)
{
int res=0;
for(int i=x;i;i-=lowbit(i)) res+=tr[i];
return res;
}
int main ()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++) scanf("%d",&a[i]);
for(int i=1;i<=n;i++) add(i,a[i]);
while(m--)
{
int k,x,y;
scanf("%d%d%d",&k,&x,&y);
if(k==0) printf("%d\n",query(y)-query(x-1));
else add(x,y);
}
return 0;
}
边栏推荐
猜你喜欢

Keil软件中map文件解析

Detailed explanation of numpy multidimensional array ndarray

The calculation and source code of the straight line intersecting the space plane

Go uses freecache for caching

万能js时间日期格式转换

2020 ACM | MoFlow: An Invertible Flow Model for Generating Molecular Graphs

Go 使用mencached缓存

The CTO said I was not advised to use SELECT *, why is that?

Universal js time date format conversion

从追赶到超越,国产软件大显身手
随机推荐
万能js时间日期格式转换
What new materials are used in the large aircraft C919?
The Society of Mind - Marvin Minsky
便携小风扇PD取电芯片
千万级数据量的表,怎样最快速度查询?
Go uses the mencached cache
《心智社会》—马文·明斯基
New material under the plastic restriction order - polylactic acid (PLA)
MySQL master-slave replication configuration construction, one step in place
AI can identify race from X-rays, but no one knows why
The first artificial intelligence safety competition officially launched
ETL为什么经常变成ELT甚至LET?
How does Redis prevent oversold and inventory deduction operations?
云服务器零基础部署网站(保姆级教程)
Calculate the inverse source of the matrix (using the adjoint matrix, a 3x3 matrix)
Ali two sides: Sentinel vs Hystrix comparison, how to choose?
export , export default,import完整用法
不会吧,Log4j 漏洞还没有完全修复?
从追赶到超越,国产软件大显身手
numpy 多维数组ndarray的详解