[6] segment tree algorithm #

If I remember correctly, it should be a # 6.

Today, we get to know a little basic tree line, but because of other data structures and algorithms are not fully understood (can not handle questions clothes) so that is a goo off rather than get.

First, do some construction segment tree.
Space is essentially a hierarchical binary numbers, for a total of probably \ (2n \) around, pay attention to not drive smaller.

1~8
1~4 5~8
1~2 3~4 5~6 7~8
1 2 3 4 | 5 6 7 8

Probably like this, a first layer \ (2 ^ 0 \) node, an i layer \ (2 ^ {i-1 } \) nodes.

Each node carry additional information with respect to the segment, (general data for different sizes, the size of the additional information should be the same otherwise there is no practical significance of the data structure.)

For each query interval, if it contains the right sub-interval, then recursively the right to enter the sub-interval, if the interval contains child left, left recursion enter the sub-query intervals and change the size range until the range of the current node's fully fit the query interval. That is, the original query section we become no more than a log interval length (is that right?) And the line segment. Well understood, right? We on the board.

int ql,qr;
<modify> query(int o,int l,int r){
    int m=l+(r-l)/2,ans=<modify>;
    if(ql<=l&&r<=qr)
        return <res>[o];
    if(ql<=m)
        ans=<modify>(ans,query(o*2,l,m));
    if(qr>m)
        ans=<modify>(ans,query(o*2+1,m+1,r));
    return ans;
}

This code is good weird wind ah ...... here is the query, modify my code to new wind sent.

int lb[maxn*2],rb[maxn*2];
<modify> query(int o,int l,int r){
    int m=lb[o]+(rb[o]-lb[o])/2,ans=<modify>;
    if(lb[o]==l&&r==rb[o])
        return <res>[o];
    if(l<=m)
        ans=<modify>(ans,query(o*2,l,m));
    if(r>m)
        ans=<modify>(ans,query(o*2+1,m+1,r));
    return ans;
}

In theory there is no problem? Since both l and r can be pre-treated well.
Then the update, modify a single point.

int p,v;
void update(int o,int l,int r){
    int m=l+(r-l)/2;
    if(l==r)
        <res>[o]=v;
    else {
        if(p<=m)
            update(o*2,l,m);
        else update(o*2+1,m+1,r);
        <res>[o]=<modify>(<res>[o*2],<res>[o*2+1]);
    }
}

Then the construction process, of course, for each point update operation is also possible, but the complexity is nlogn, if the pre-set value of each leaf node recursively configuration can achieve linear complexity of n.

int a[maxn];
void build(int o,int l,int r){
    m=l+(r-l)/2;
    if(l==r)
        <res>[o]=a[o-maxn+1];
    else {
        build(o*2,l,m);
        build(o*2+1,m+1,r);
        <res>[o]=<modify>(<res>[o*2],<res>[o*2+1]);
    }
}

It is probably the case, point modify, update, query. I learned again to add back.

Guess you like

Origin www.cnblogs.com/Schwarzkopf-Henkal/p/11840446.html