定義:
線段樹是一種二叉搜尋樹,與區間樹相似,它將乙個區間劃分成一些單元區間,每個單元區間對應線段樹中的乙個葉結點。
對於線段樹中的每乙個非葉子節點[a,b],它的左兒子表示的區間為[a,(a+b)/2],右兒子表示的區間為[(a+b)/2+1,b]。因此線段樹是平衡二叉樹,最後的子節點數目為n,即整個線段區間的長度。使用線段樹可以快速的查詢某乙個節點在若干條線段**現的次數,時間複雜度為o(logn)。而未優化的空間複雜度為2n,因此有時需要離散化讓空間壓縮。
public
class
segmenttree
private
void
buildsegmenttree
(int treeindex,
int l,
int r)
int m =
(l + r)
>>>1;
int leftindex =
leftchildindex
(treeindex)
;int rightindex =
rightchildindex
(treeindex)
;buildsegmenttree
(leftindex, l, m)
;buildsegmenttree
(rightindex, m +
1, r)
; tree[treeindex]
= merger.
merge
(tree[leftindex]
, tree[rightindex]);
}public e query
(int queryl,
int queryr)
return
query(0
,0, data.length -
1, queryl, queryr);}
private e query
(int treeindex,
int l,
int r,
int queryl,
int queryr)
int mid =
(l + r)
>>>1;
int leftchildindex =
leftchildindex
(treeindex)
;int rightchildindex =
rightchildindex
(treeindex);if
(queryl >= mid +1)
else
if(queryr <= mid)
e leftans =
query
(leftchildindex, l, mid, queryl, mid)
; e rightans =
query
(rightchildindex, mid +
1, r, mid +
1, queryr)
;return merger.
merge
(leftans, rightans);}
public
void
set(
int index, e e)
data[index]
= e;
set(0,
0, data.length -
1, index, e);}
private
void
set(
int treeindex,
int l,
int r,
int index, e e)
int mid =
(l + r)
>>>1;
int leftchildindex =
leftchildindex
(treeindex)
;int rightchildindex =
rightchildindex
(treeindex);if
(index >= mid +1)
else
if(index <= mid)
tree[treeindex]
= merger.
merge
(tree[leftchildindex]
, tree[rightchildindex]);
}private
intrightchildindex
(int treeindex)
private
intleftchildindex
(int treeindex)
public
intgetsize()
public
static
void
main
(string[
] args)
, integer:
:sum)
; system.out.
println
(segtree.
query(0
,3))
; system.out.
println
(segtree.
query(0
,4))
; system.out.
println
(segtree.
query(0
,1))
; segtree.
set(0,
0); system.out.
println
(segtree.
query(0
,3))
;}}inte***ce
merger
線段樹模板(模板)
參考部落格 持續更新。外鏈轉存失敗,源站可能有防盜煉機制,建議將儲存下來直接上傳 img xhrgdjcd 1613976863463 區間儲存在陣列中的下標對應為 12 3 4 5 6 7 8 9 10 11 12 13 14 15 四部分單點更新 根據題目的要求編寫自己的pushup,query...
線段樹模板
include include include using namespace std const int size 10010 struct node the node of line tree class linetree void updatem void updateline public ...
線段樹模板
單點更新,區間求最值 include include include include include define n 222222 using namespace std int num n struct tree tree n 4 void push up int root void build...