树的结构 数据结构_段树| 数据结构
樹的結(jié)構(gòu) 數(shù)據(jù)結(jié)構(gòu)
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.
段樹是完整的二叉樹,其中每個(gè)節(jié)點(diǎn)代表一個(gè)間隔。 節(jié)點(diǎn)可以存儲(chǔ)一個(gè)或多個(gè)間隔的數(shù)據(jù)成員,以后可以查詢?cè)摮蓡T。
Why do we need Segment tree?
為什么我們需要細(xì)分樹?
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.
許多問題要求我們根據(jù)對(duì)可用數(shù)據(jù)范圍或數(shù)據(jù)段的查詢得出結(jié)果。 這可能是一個(gè)繁瑣而緩慢的過程,尤其是在查詢數(shù)量很大的情況下。
A segment tree lets us process such queries efficiently in logarithmic order of time.
段樹使我們能夠以對(duì)數(shù)時(shí)間順序有效地處理此類查詢。
How do we make a Segment tree?
我們?nèi)绾沃谱骷?xì)分樹?
Let the data be in array arr[]
讓數(shù)據(jù)位于數(shù)組arr []中
The root of our tree will represent the entire interval of data we are interested in, i.e, arr[0...n-1].
樹的根將代表我們感興趣的整個(gè)數(shù)據(jù)間隔,即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].
樹的每片葉子將代表一個(gè)僅包含一個(gè)元素的范圍。 因此,葉子代表arr [0] , arr [1] , arr [2] ... arr [n-1] 。
The internal nodes will represent the merged result of their child nodes.
內(nèi)部節(jié)點(diǎn)將代表其子節(jié)點(diǎn)的合并結(jié)果。
Each of the children nodes could represent approximately half of the range represented by their parent.
每個(gè)子節(jié)點(diǎn)可代表其父節(jié)點(diǎn)所代表范圍的大約一半。
Segment Tree generally contains three types of method: Build, Query, and Update.
細(xì)分樹通常包含三種類型的方法:生成,查詢和更新。
Let’s take an example:
讓我們舉個(gè)例子:
Problem: Range minimum query
問題:范圍最小查詢
You are given N numbers and Q queries. There are two types of queries.
系統(tǒng)會(huì)為您提供N個(gè)數(shù)字和Q個(gè)查詢。 有兩種類型的查詢。
Find the minimum number in range [l,r].
在[l,r]范圍內(nèi)找到最小值。
Update the element at ith position of array to val.
將數(shù)組第 i 個(gè)位置的元素更新為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(查詢)是一個(gè)非常大的數(shù)字,它將非常慢。
But it can be solved in logarithmic time with segment trees.
但這可以用段樹在對(duì)數(shù)時(shí)間內(nèi)解決。
The root of the tree is at index 1
樹的根在索引1處
The children then will be at 2*i and 2*i+1 index.
然后,子級(jí)將位于2 * i和2 * i + 1索引處。
翻譯自: https://www.includehelp.com/data-structure-tutorial/segment-trees.aspx
樹的結(jié)構(gòu) 數(shù)據(jù)結(jié)構(gòu)
總結(jié)
以上是生活随笔為你收集整理的树的结构 数据结构_段树| 数据结构的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: java的equals方法_Java D
- 下一篇: kotlin 扩展类的功能_Kotlin