線段樹 模板

2021-08-06 02:52:47 字數 1598 閱讀 5881

線段樹是一種

二叉搜尋樹

,與區間樹

相似,它將乙個區間劃分成一些單元區間,每個單元區間對應線段樹中的乙個葉結點

void build(int o,int l,int r) //建樹

int mid=(l+r)/2;

build(o*2,l,mid);

build(o*2+1,mid+1,r);

pushup(o);

}void update(int o,int l,int r,int x,int y) //把節點x的資料更新為y

int mid=(l+r)/2;

if(x > mid) //更新的節點在右邊;

update(o*2+1,mid+1,r,x,y);

else // 節點在左邊;

update(o*2,l,mid,x,y);

pushup(o); //更新當前節點資料

}int findsum(int o,int l,int r,int x,int y) //查詢x到y的和

int mid = (l+r) / 2;

if(y<=mid)

return findsum(o*2,l,mid,x,y);

else if(x>mid)

return findsum(o*2+1,mid+1,r,x,y);

else

return findsum(o*2,l,mid,x,mid)+findsum(o*2+1,mid+1,r,mid+1,y);

} int findmax(int o,int l,int r,int x,int y)

int mid = (l+r) / 2;

if(y<=mid)

return findmax(o*2,l,mid,x,y);

else if(x>mid)

return findmax(o*2+1,mid+1,r,x,y);

else

return max( findmax(o*2,l,mid,x,mid), findmax(o*2+1,mid+1,r,mid+1,y) );

}int findmin(int o,int l,int r,int x,int y)

int mid = (l+r) / 2;

if(y<=mid)

return findmin(o*2,l,mid,x,y);

else if(x>mid)

return findmin(o*2+1,mid+1,r,x,y);

else

return min( findmin(o*2,l,mid,x,mid), findmin(o*2+1,mid+1,r,mid+1,y) );

}int main()/*4

1 3 2 6

*/

線段樹模板(模板)

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