树状数组
来源:互联网 发布:盐和避难所 mac 中文 编辑:程序博客网 时间:2024/05/18 13:24
代码包含树状数组:建立,更新,加减运算,求和。和线段树类似,但比线段树简单,而且:x&(-x)代表2的k次幂,也就是lowbit(X),就是加上x的从最低位1开始的数,树状数组的分组有一个特点:分的区间不会交叉。加和是就要x-=x&(-x)
更新和加减就要x+=x&(-x)
#include<iostream>#include<cstring>#include<cstdio>const int maxn=1000;using namespace std;int c[maxn];int a[maxn];int getsum(int x){ int sum=0; while(x>0) { sum+=c[x]; x-=x&(-x); } return sum;}void add(int x,int v){ a[x]+=v; while(x<=maxn) { c[x]+=v; x+=x&(-x); }}void change(int x,int v){ int temp=v-a[x]; a[x]=v; while(x<=maxn) { c[x]+=temp; x+=x&(-x); }}int main(){ add(12,12); change(11,2); change(8,8); cout<<getsum(12)<<endl; add (10,10); cout<<getsum(12)<<endl; change (10,5); cout<<getsum(12)<<endl; return 0;}
0 0
- 树状数组
- 树状数组
- 树状数组
- 树状数组
- 树状数组
- 树状数组
- 树状数组
- 树状数组
- 树状数组
- 树状数组
- 树状数组
- 树状数组
- 树状数组
- 树状数组
- 树状数组
- 树状数组
- 树状数组
- 树状数组
- Tomcat项目部署方式
- 【mkdir】创建目录
- 使用 CXF 做 webservice 简单例子
- 使用js实现全选、反选功能
- Android补间动画效果translate、scale、alpha、rotate详解(带源码)XML实现
- 树状数组
- 理解MySQL——索引与优化
- hive学习总结(9)—数据库创建、表创建、加载数据
- 【pwd】显示当前目录
- Error: EACCES: permission denied, access '/usr/local/lib/node_modules' npm ERR! at Error (native)
- poj 2503 trie树
- 每天一个linux命令(48):watch命令
- 【chage】修改账号或密码的有效期限
- spoj CPTTRN7 - Character Patterns (Act 7)