Data structure: Detailed implementation of line segment tree

The essence is a tree structure with left and right endpoints added

segment tree

data type construct

struct node{
    
    
	int l,r;  //l左端点    r右端点
	int val;  //val值域
}n[maxn];     //n[i]表示标号为i的树的结点

basic operation

Constructing a Segment Tree

void make(int left,int right, int num);

Parameter Description:

left—right: the left endpoint—the right endpoint, the maximum interval;

num: label, generally 1.

add node

void add(int i,int j,int num);

Parameter Description:

i: the destination point to be added;

j: the number of points to be added;

num: label, generally 1.

delete node

void sub(int i,int j,int num);

Parameter Description:

i: the destination point to be added;

j: the number of points to be added;

num: label, generally 1.

query node

void query(int l, int r,int num);

Parameter Description:

lr: query interval, this function will use the sum of weights stored in sum to query the number of lr;

num: label, generally 1.

Realization principle

Constructing a Segment Tree

Nature of use:

1> For a node labeled i, its left child is labeled 2i, its right child is labeled 2i+1, and its father is labeled i/2;

2> In the line segment tree, a point whose two ends are a and b, the two ends of its left child are a, mid, and the two ends of its right child are mid+1, b;

3> When the left and right endpoints are equal, the leaf node is accessed

Ideas:

for each node

Created with Raphaël 2.2.0 确定左右端点lr 递归询问左孩子 递归询问右孩子 计算val值

val is calculated as: val = left.val + right.val

add node

The operation of the top-down tree, the operation of adding from the root to the node.

Ideas:

Visit from the root down, if i is in the left child interval, then + j, otherwise visit the right child. ( i is not in the left child, it must be in the right child )

Start from the root and stop at the leaf nodes

Created with Raphaël 2.2.0 val+j 左孩子是否包含i? 递归访问左孩子 递归访问右孩子 yes no

delete node

Add the inverse operation of the node, just change '+' to '-'.

query node

Let the two ends of the current point be a, b, and the two ends of the target point be l, r

use taxonomy

Which section l and r are in, visit which section

Ideas:

Created with Raphaël 2.2.0 l-r是否包含a-b 记录权值和 l,r在左孩子中? 递归访问左孩子 l,r在右孩子中? 递归访问右孩子 l,r在左、右孩子中? 递归访问左右孩子 yes no yes no yes no yes

C++ code implementation

Build a segment tree

void make(int x, int y, int num){
    
    //构造
	t[num].l=x,t[num].r=y;
	if(x==y)
		t[num].val=val;  //到叶子结点赋值,结束
	else{
    
    
		make(x, ( x + y ) / 2, 2 * num);//递归构造左子树
		make(( x + y ) / 2 + 1, y, 2 * num + 1);//递归构造右子树
		t[num].val = t[2*num].val + t[2*num+1].val;//计算val
	}	
}

add node

void add(int i, int j, int num){
    
    //增加
	t[num].val += j;//val+j
	if(t[num].l==i && t[num].r==i)//找到结点
		return;
	if(i>(t[num].l + t[num].r) / 2)//i在右孩子中
		add(i, j, 2 * num + 1);
	else						//i在左孩子中
		add(i, j, 2 * num);
}

delete node

void add(int i, int j, int num){
    
    //增加
	t[num].val -= j;//val+j
	if(t[num].l==i && t[num].r==i)//找到结点
		return;
	if(i>(t[num].l + t[num].r) / 2)//i在右孩子中
		add(i, j, 2 * num + 1);
	else						//i在左孩子中
		add(i, j, 2 * num);
}

query node

void query(int l, int r, int num){
    
    //查询
	if(l<=t[num].l && r>=t[num].r)//在目标区间内,记录权值和SUM
		SUM += t[num].val;
	else{
    
    			//不在目标区间内,进行分类
		int mid = (t[num].l + t[num].r)/2;
		if(l>mid)//在右孩子中
			query(l, r, 2 * num + 1);
		else if(r<=mid)//在左孩子中
			query(l, r, 2 * num);
		else{
    
    //左右孩子中均有
			query(l, r, 2 * num);
			query(l, r, 2 * num + 1);
		}
	}
}

Lazy tags optimization

Interval update: modify the value of a continuous interval

Lazy tags optimization:

As the name suggests, lazy mark optimization ( as we all know, lazy people create efficiency )

The key idea: when modifying, only modify the points that are useful for the query, and mark the points that are not completely updated_lazily_, and update them when needed

Example application

  1. P3372 [Template] Line Segment Tree 1
    Title Description:
         For example, given a sequence of numbers, you need to perform the following two operations:
        1. Add k to each number in a certain interval.
        2. Find the sum of each number in a certain interval.
    code show as below:
#include<iostream>
#include<cstdio>
#define MAXN 1000001
#define ll long long
using namespace std;
unsigned ll n,m,a[MAXN],ans[MAXN<<2],tag[MAXN<<2];
inline ll ls(ll x)
{
    
    
    return x<<1;
}
inline ll rs(ll x)
{
    
    
    return x<<1|1;
}
void scan()
{
    
    
    cin>>n>>m;
    for(ll i=1;i<=n;i++)
    scanf("%lld",&a[i]);
}
inline void push_up(ll p)
{
    
    
    ans[p]=ans[ls(p)]+ans[rs(p)];
}
void build(ll p,ll l,ll r)
{
    
    
    tag[p]=0;
    if(l==r){
    
    ans[p]=a[l];return ;}
    ll mid=(l+r)>>1;
    build(ls(p),l,mid);
    build(rs(p),mid+1,r);
    push_up(p);
} 
inline void f(ll p,ll l,ll r,ll k)
{
    
    
    tag[p]=tag[p]+k;
    ans[p]=ans[p]+k*(r-l+1);
}
inline void push_down(ll p,ll l,ll r)
{
    
    
    ll mid=(l+r)>>1;
    f(ls(p),l,mid,tag[p]);
    f(rs(p),mid+1,r,tag[p]);
    tag[p]=0;
}
inline void update(ll nl,ll nr,ll l,ll r,ll p,ll k)
{
    
    
    if(nl<=l&&r<=nr)
    {
    
    
        ans[p]+=k*(r-l+1);
        tag[p]+=k;
        return ;
    }
    push_down(p,l,r);
    ll mid=(l+r)>>1;
    if(nl<=mid)update(nl,nr,l,mid,ls(p),k);
    if(nr>mid) update(nl,nr,mid+1,r,rs(p),k);
    push_up(p);
}
ll query(ll q_x,ll q_y,ll l,ll r,ll p)
{
    
    
    ll res=0;
    if(q_x<=l&&r<=q_y)return ans[p];
    ll mid=(l+r)>>1;
    push_down(p,l,r);
    if(q_x<=mid)res+=query(q_x,q_y,l,mid,ls(p));
    if(q_y>mid) res+=query(q_x,q_y,mid+1,r,rs(p));
    return res;
}
int main()
{
    
    
    ll a1,b,c,d,e,f;
    scan();
    build(1,1,n);
    while(m--)
    {
    
    
        scanf("%lld",&a1);
        switch(a1)
        {
    
    
            case 1:{
    
    
                scanf("%lld%lld%lld",&b,&c,&d);
                update(b,c,1,n,1,d);
                break;
            }
            case 2:{
    
    
                scanf("%lld%lld",&e,&f);
                printf("%lld\n",query(e,f,1,n,1));
                break;
            }
        }
    }
    return 0;
}

  1. P3373 [Template] Line Segment Tree 2
    Topic description:
         As in the title, given a sequence of numbers, you need to perform the following three operations:
        1. Multiply each number in a certain interval by x
        2. Add x to each number in a certain interval
        3. Find The code for the sum of each number in a certain interval
    is as follows:
#include <iostream>
#include <cstdio>
using namespace std;
//题目中给的p
int p;
//暂存数列的数组
long long a[100007];
//线段树结构体,v表示此时的答案,mul表示乘法意义上的lazytag,add是加法意义上的
struct node{
    
    
    long long v, mul, add;
}st[400007];
//buildtree
void bt(int root, int l, int r){
    
    
//初始化lazytag
    st[root].mul=1;
    st[root].add=0;
    if(l==r){
    
    
        st[root].v=a[l];
    }
    else{
    
    
        int m=(l+r)/2;
        bt(root*2, l, m);
        bt(root*2+1, m+1, r);
        st[root].v=st[root*2].v+st[root*2+1].v;
    }
    st[root].v%=p;
    return ;
}
//核心代码,维护lazytag
void pushdown(int root, int l, int r){
    
    
    int m=(l+r)/2;
//根据我们规定的优先度,儿子的值=此刻儿子的值*爸爸的乘法lazytag+儿子的区间长度*爸爸的加法lazytag
    st[root*2].v=(st[root*2].v*st[root].mul+st[root].add*(m-l+1))%p;
    st[root*2+1].v=(st[root*2+1].v*st[root].mul+st[root].add*(r-m))%p;
//很好维护的lazytag
    st[root*2].mul=(st[root*2].mul*st[root].mul)%p;
    st[root*2+1].mul=(st[root*2+1].mul*st[root].mul)%p;
    st[root*2].add=(st[root*2].add*st[root].mul+st[root].add)%p;
    st[root*2+1].add=(st[root*2+1].add*st[root].mul+st[root].add)%p;
//把父节点的值初始化
    st[root].mul=1;
    st[root].add=0;
    return ;
}
//update1,乘法,stdl此刻区间的左边,stdr此刻区间的右边,l给出的左边,r给出的右边
void ud1(int root, int stdl, int stdr, int l, int r, long long k){
    
    
//假如本区间和给出的区间没有交集
    if(r<stdl || stdr<l){
    
    
        return ;
    }
//假如给出的区间包含本区间
    if(l<=stdl && stdr<=r){
    
    
        st[root].v=(st[root].v*k)%p;
        st[root].mul=(st[root].mul*k)%p;
        st[root].add=(st[root].add*k)%p;
        return ;
    }
//假如给出的区间和本区间有交集,但是也有不交叉的部分
//先传递lazytag
    pushdown(root, stdl, stdr);
    int m=(stdl+stdr)/2;
    ud1(root*2, stdl, m, l, r, k);
    ud1(root*2+1, m+1, stdr, l, r, k);
    st[root].v=(st[root*2].v+st[root*2+1].v)%p;
    return ;
}
//update2,加法,和乘法同理
void ud2(int root, int stdl, int stdr, int l, int r, long long k){
    
    
    if(r<stdl || stdr<l){
    
    
        return ;
    }
    if(l<=stdl && stdr<=r){
    
    
        st[root].add=(st[root].add+k)%p;
        st[root].v=(st[root].v+k*(stdr-stdl+1))%p;
        return ;
    }
    pushdown(root, stdl, stdr);
    int m=(stdl+stdr)/2;
    ud2(root*2, stdl, m, l, r, k);
    ud2(root*2+1, m+1, stdr, l, r, k);
    st[root].v=(st[root*2].v+st[root*2+1].v)%p;
    return ;
}
//访问,和update一样
long long query(int root, int stdl, int stdr, int l, int r){
    
    
    if(r<stdl || stdr<l){
    
    
        return 0;
    }
    if(l<=stdl && stdr<=r){
    
    
        return st[root].v;
    }
    pushdown(root, stdl, stdr);
    int m=(stdl+stdr)/2;
    return (query(root*2, stdl, m, l, r)+query(root*2+1, m+1, stdr, l, r))%p;
}
int main(){
    
    
    int n, m;
    scanf("%d%d%d", &n, &m, &p);
    for(int i=1; i<=n; i++){
    
    
        scanf("%lld", &a[i]);
    }
    bt(1, 1, n);
    while(m--){
    
    
        int chk;
        scanf("%d", &chk);
        int x, y;
        long long k;
        if(chk==1){
    
    
            scanf("%d%d%lld", &x, &y, &k);
            ud1(1, 1, n, x, y, k);
        }
        else if(chk==2){
    
    
            scanf("%d%d%lld", &x, &y, &k);
            ud2(1, 1, n, x, y, k);
        }
        else{
    
    
            scanf("%d%d", &x, &y);
            printf("%lld\n", query(1, 1, n, x, y));
        }
    }
    return 0;
}

Guess you like

Origin blog.csdn.net/BWQ2019/article/details/110481438