Preliminary learning segment tree

                                                A few days ago to learn the tree split chain, adjusting for a long time and found a tree line write hung up and decided to write a blog summary. ---- Author

    If a set of numbers for you, you do the required number of operations, there are two operations: 1, plus the number of a section k. 2, the query interval and an interval

  Clearly, we can accomplish this with two operating complexity O (N) time.

  But if the number N of operation and scale is very large, such as to achieve the scale of 10 ^ 5, then the simple approach too slow. Therefore, we need a new thing - tree line.

  What is the tree line (Segment Tree)?

  Segment tree is a binary search tree, interval tree, and similar, it is divided into a number of unit intervals interval, a leaf node corresponding to each unit section of the segment tree. For each non-leaf node segment tree [a, b], the interval its left son represented by [a, (a + b) / 2], segment the right son represented by [(a + b) / 2 + 1, b]. Therefore segment tree is a balanced binary tree, the last number of child nodes is N, i.e., the entire length of the line section. (Excerpt from Baidu Encyclopedia).

  Simply means that the information in each node on the tree in a storage section, the son of a point around the point stored respectively store the left half and the right half of the interval range.

  For chestnuts, if we give a set of numbers 1,2,6,3,8,9,5,7,4,5, we want to save each interval and the interval. Then the segment tree is probably a long way:

              

                              (Each node of the storage node and the representative section section)

 

  What segment tree can be done?

  Support number of segments: a single point / range modification (Update)

           2 single point / range query (query)

    Their time complexity is O (log n) of

  Practice (thinking)

  Achievements (Build) : We want every half an interval, and then were stored in about sons, the process is similar, so we can use recursion to complete achievements. When the interval length is 1, the value of the number of our series of numbers stored in the leaf node, and then passed up.

  

     

  更新(update):如果我们要更新某一段区间A的值,那么显然我们不仅要更新A所在的节点,同时要更新A所包含的区间,和包含A的区间。

  我们依然递归完成这个任务,但update和build有一些区别,我们来思考。(下面的假设请对照上图)

  假如我们要修改[2,2] , 那么我们直接简单的递归到[2,2]然后向上更新父节点的值即可。

  假如我们要更新[4,6],那么问题来了,这个区间处在两个子树中,我们无法找到直接代表这个区间的节点。但这样我们就没办法修改了吗?不是的。我们可以把[4,6]拆成[4,5]和[6,6]分别修改。这只需要在向下递归时加一个判断。

  查询(query):查询的步骤和更新是相似的。

    干巴巴的说不知道大家能不能看懂。我们来看一下代码实现。

  用结构体储存

1 struct Tree{
2     int l,r,sum;
3 }tree[N*4];//N是数列长度,我们通过图可以很清楚的发现节点个数是数列长度的4倍多一点

 

  build函数的实现

待更新~

 

Guess you like

Origin www.cnblogs.com/FoxC/p/11222068.html