线段树的基础应用
来源:互联网 发布:js获取字符串的下标 编辑:程序博客网 时间:2024/04/29 10:37
(一)线段树的基本机构
1.时间复杂度
我们之所以使用线段树是因为它很多的操作都是o(log n)的
一个有n的叶子节点的树其深度约为log n
所以如果某个操作的在线段树复杂度为n将失去意义
2.空间复杂度
大约为叶子节点的4倍
3.线段树的信息收集
线段树父节点的信息可以利用up()从子节点提取的
同时线段树树上可以通过down()将父节点的信息给子节点
void tree(int l,int r,int p){ //…… up(); tree(l,r,p*2); tree(l,r,p*2+1); down();}
4.建树
void build(int L,int R,int p){ tree[p].L=L,tree[p].R=R; if(L==R)return; int mid=(L+R)/2; down(p); build(L,mid,2*p);build(mid+1,R,2*p+1); up(p);}
(二)线段树的基本功能
以求区间和为例
1.单点跟新
void update(int x,int a,int p){ if(tree[p].L==tree[p].R){tree[p].sum=a;return;} int mid=tree[p].mid(); down(p); if(x<=mid)update(x,a,2*p); else update(x,a,2*p+1); up(p);}
2.区间跟新
利用down函数进行延迟跟新
void down(int p){ tree[2*p].add+=tree[p].add; tree[2*p+1].add+=tree[p].add; tree[2*p].sum+=tree[p].add*(tree[2*p].r-tree[2*p].l+1); tree[2*p+1].sum+=tree[p].add*(tree[2*p+1].r-tree[2*p+1].l+1); tree[p].add=0;}void update(int l,int r,int c,int p){ if(tree[p].add)down(p); if(r<tree[p].l||l>tree[p].r)return; if(l<=tree[p].l&&r>=tree[p].r){ tree[p].add+=c; return; } update(l,r,c,2*p);update(l,r,c,2*p+1); up(p);}
3.单点查询
int query(int x,int p){ if(tree[p].l==tree[p].r)return tree[p].sum; int mid=tree.mid(); if(r<=mid)return query(x,p*2); else return query(x,2*p+1);}
4.区间查询
int query(int L,int R,int p){ if(tree[p].L==L&&tree[p].R==R)return tree[p].sum; int mid=tree[p].mid(); if(R<=mid)return query(L,R,2*p); if(mid<L)return query(L,R,2*p+1); return query(L,mid,2*p)+query(mid+1,R,2*p+1);}
3 0
- 线段树的基础应用
- 线段树的应用
- 线段树的应用
- poj3468_线段树的应用
- 线段树的简单应用
- 线段树的一系列应用
- lintcode线段树的应用
- 线段树的基础介绍
- 线段树基础与模板与简单应用
- zoj1610-线段树的应用(线段覆盖)
- 线段树应用:线段覆盖
- 线段树的应用-poj3264的解法
- 线段树的应用-poj3468的解法
- 线段树的应用-poj2777的解法
- 线段树的基础递归的使用
- 线段树的应用——刷墙
- 线段树的应用及模版
- hdu1394(线段树点更新的应用)
- 自定义Dialog之信息提示
- hbase权限管理
- echart图表控件配置入门(常用图表数据动态绑定)
- 解决X64操作系统PL/SQL连接报错问题 make sure you have the 32 bits oracle client installed
- 一些maven命令
- 线段树的基础应用
- 关于UIViewController添加UINavigationBar的详细实现方法
- appium 滑动
- C语言的fopen函数(文件操作/读写)
- sublime各种插件
- Node.js入门---上传图片
- 3.1 Git 分支 - 分支简介
- c sharp -- 多态例子
- 文章标题