線段樹(模板)

2021-09-26 01:25:12 字數 1173 閱讀 9854

**

線段樹是乙個神奇的資料結構。

對於普通的線性結構對其進行區間上的修改複雜度為o(n),對於n特別大的情況或者修改特別多次數的話仍然會tle,這個時候就應該使用樹形資料結構,它會把單個修改的複雜度降為o(lgn)。

所以就需要線段樹了。。

線段樹可以實現單點修改,單點查詢,區間修改,區間查詢等功能。

樹的定義

#define ls k<<1

#define rs k<<1|1

#define maxn 100008

struct h;

h a[maxn*4];//maxn為資料量,保險起見最好把陣列開到4倍

建樹

void build(int k,int l,int r)

int mid=(l+r)>>1;

build(ls,l,mid);

build(rs,mid+1,r);

update(k);

}

單點修改

void change(int k,int x,int y)

int mid=(a[k].l+a[k].r)>>1;

if(x<=mid)

change(ls,x,y);

else

change(rs,x,y);

update(k);

}

區間修改

void changesegment(int k,int l,int r,int x)

pushdown(k);//延遲標記下傳

int mid=(a[k].l+a[k].r)>>1;

if(r>mid) changesegment(rs,l,r,x);

if(l<=mid) changesegment(ls,l,r,x);

update(k);

}

區間查詢

long long query(int k,int l,int r)
更新

void update(int k)
延遲標記下傳

void pushdown(int k)

}

線段樹模板(模板)

參考部落格 持續更新。外鏈轉存失敗,源站可能有防盜煉機制,建議將儲存下來直接上傳 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...