對於有些問題,關注的是線段(區間)
0層 - 1
1層 - 2
3層 - 4
3層 - 8
....
h-1 層 - 2 ^ (h-1)
package tree;
public
inte***ce
merger
package tree;
public
class
segmenttree
tree =
(e)new
object[4
* arr.length]
;buildsegmenttree(0
,0, data.length -1)
;}// 在treeindex 的位置建立表示區間 [l,r] 的線段樹
private
void
buildsegmenttree
(int treeindex,
int l,
int r)
int lefttreeindex =
leftchild
(treeindex)
;int righttreeindex =
rightchild
(treeindex)
;int mid = l +
(r - l)/2
;buildsegmenttree
(lefttreeindex, l, mid)
;buildsegmenttree
(righttreeindex, mid +
1, r)
; tree[treeindex]
= merger.
merge
(tree[lefttreeindex]
, tree[righttreeindex]);
}public
intgetsize()
public e get
(int index)
return data[index];}
// 返回完全二叉樹的陣列表示中,乙個索引所表示的元素的左孩子
private
intleftchild
(int index)
private
intrightchild
(int index)
@override
public string tostring()
else
if( i != tree.length-1)
} res.
(']');
return res.
tostring()
;}}
package tree;
public
class
main
;// segmenttreesegtree = new segmenttree<>(nums, new merger()
// });
segmenttree
segtree =
newsegmenttree
<
>
(nums,
(a, b)
-> a + b)
; system.out.
println
(segtree);}
}
[-3, 1, -4, -2, 3, -3, -1, -2, 0, null, null, -5, 2, null, null, null, null, null, null, null, null, null, null, null]
process finished with exit code 0
初步認識線段樹(1)線段樹用途 建樹
當你遇到了這樣的題目時 現在請求你維護乙個數列,要求提供以下兩種操作 1 查詢操作。語法 q l 功能 查詢當前數列中末尾l個數中的最大的數,並輸出這個數的值。限制 l不超過當前數列的長度。l 0 2 插入操作。語法 a n 功能 將n加上t,其中t是最近一次查詢操作的答案 如果還未執行過查詢操作,...
線段樹基礎(1)
訓練了三周線段樹,對線段樹的點操作 斷更新和常見應用範圍進行總結,並記錄一些技巧。線段樹是一種二叉搜尋樹,也是一顆平衡樹。樸素的遞迴寫法是對於每乙個非葉子節點 l,r 取m l r 2,左孩子為 l,m 右孩子為 m 1,r 使用堆式儲存,空間大小為4n。一些define define lc rt ...
線段樹入門(1)
題目描述 description 一行n個方格,開始每個格仔裡都有乙個整數。現在動態地提出一些問題和修改 提問的形式是求某乙個特定的子區間 a,b 中所有元素的和 修改的規則是指定某乙個格仔x,加上或者減去乙個特定的值a。現在要求你能對每個提問作出正確的回答。1 n 100000,提問和修改的總數m...