树的结构 数据结构_段树| 数据结构
樹的結構 數據結構
What is a segment tree?
什么是段樹?
A segment tree is a full binary tree where each node represents an interval. A node may store one or more data members of an interval which can be queried later.
段樹是完整的二叉樹,其中每個節點代表一個間隔。 節點可以存儲一個或多個間隔的數據成員,以后可以查詢該成員。
Why do we need Segment tree?
為什么我們需要細分樹?
Many problems require that we give results based on query over a range or segment of available data. This can be the tedious and slow process, especially if the number of queries is large.
許多問題要求我們根據對可用數據范圍或數據段的查詢得出結果。 這可能是一個繁瑣而緩慢的過程,尤其是在查詢數量很大的情況下。
A segment tree lets us process such queries efficiently in logarithmic order of time.
段樹使我們能夠以對數時間順序有效地處理此類查詢。
How do we make a Segment tree?
我們如何制作細分樹?
Let the data be in array arr[]
讓數據位于數組arr []中
The root of our tree will represent the entire interval of data we are interested in, i.e, arr[0...n-1].
樹的根將代表我們感興趣的整個數據間隔,即arr [0 ... n-1] 。
Each leaf of the tree will represent a range consisting of just a single element. Thus the leaves represent arr[0], arr[1], arr[2] ... arr[n-1].
樹的每片葉子將代表一個僅包含一個元素的范圍。 因此,葉子代表arr [0] , arr [1] , arr [2] ... arr [n-1] 。
The internal nodes will represent the merged result of their child nodes.
內部節點將代表其子節點的合并結果。
Each of the children nodes could represent approximately half of the range represented by their parent.
每個子節點可代表其父節點所代表范圍的大約一半。
Segment Tree generally contains three types of method: Build, Query, and Update.
細分樹通常包含三種類型的方法:生成,查詢和更新。
Let’s take an example:
讓我們舉個例子:
Problem: Range minimum query
問題:范圍最小查詢
You are given N numbers and Q queries. There are two types of queries.
系統會為您提供N個數字和Q個查詢。 有兩種類型的查詢。
Find the minimum number in range [l,r].
在[l,r]范圍內找到最小值。
Update the element at ith position of array to val.
將數組第 i 個位置的元素更新為val 。
Basic Approach:
基本方法:
We can find minimum element in O(N) and update the element in O(1). But if N or Q (query) is a very large number, it will be very slow.
我們可以在O(N)中找到最小元素,并在O(1)中更新元素。 但是,如果N或Q(查詢)是一個非常大的數字,它將非常慢。
But it can be solved in logarithmic time with segment trees.
但這可以用段樹在對數時間內解決。
The root of the tree is at index 1
樹的根在索引1處
The children then will be at 2*i and 2*i+1 index.
然后,子級將位于2 * i和2 * i + 1索引處。
翻譯自: https://www.includehelp.com/data-structure-tutorial/segment-trees.aspx
樹的結構 數據結構
總結
以上是生活随笔為你收集整理的树的结构 数据结构_段树| 数据结构的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java的equals方法_Java D
- 下一篇: kotlin 扩展类的功能_Kotlin