1. definitions
#include <iostream> #include <cstdio> #define maxn 500000 using namespace std; struct tree { int l,r; long long w; int lazy; }tr[maxn*4];
// l, r represents the left and right subtree, w represents a value interval (value for each node), the lazy use its own details see below ---
The main problem encountered:
To resolve any calculation of an array interval length, and after random change a value in the calculation of this interval and
using segment tree can reduce the time complexity. - from O (n) is reduced to O (logn)
three main functions
1 according to the array, creating a segment tree (full binary, not complement 0)
2 changes a value updated segment tree
3. Compute LR and a section
4 and the specific operation codes (aLGORITHM)
1 void build(int l,int r,int k) 2 { 3 tr[k].l=l; 4 tr[k].r=r; 5 if(l==r) 6 { 7 scanf("%d",&tr[k].w); 8 return; 9 } 10 int mid=(l+r)/2; 11 build(l,mid,k*2); 12 build(mid+1,r,k*2+ 1 ); 13 p [k] .w = p [k * 2 ] .w + p [k * 2 + 1 ] .w; 14 }
Use here mid-half of a manifestation of thought
Again I give an example: 1--10 will build a segment tree - Figure (better understanding)
Remember - just a segment tree data structure, each of its nodes is an interval (corresponding set)
Query Interval
Quote marks chiefs from the rock> https://blog.csdn.net/zearot/article/details/52280189
Thinking query interval is the interval to be asked and is now in the range of comparison, it is easy to simulate what we know, the interval to query the only two situations: We do it on the map --- 1 example query 2-- 4 (including a node has good points (range) of - it means being left or right interval includes a set). --- 6 --- 2 query. 10 (this interval with the left and right sections intersect) - learn better collection of children's shoes it should be easy to understand
Specific code to achieve the following
void ask(int l,int r,int k) { if(tr[k].l>=l&&tr[k].r<=r) { ans+=tr[k].w; return; } if(tr[k].lazy) down(k); int mid=(tr[k].l+tr[k].r)/2; if(l<=mid) ask(l,r,k*2); if(r>mid) ask(l,r,k*2+1); //tr[k].w=tr[k*2].w+tr[k*2+1].w; }
Well ,, query and achievements on the first stop here ,, basics See below tree line - (underlying data structures) - bis