线段树的基础应用

来源:互联网 发布: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