線段樹模板

2021-10-08 08:04:27 字數 1797 閱讀 5086

const int maxn = 500005 * 4;    //線段樹範圍要開4倍

struct tree

;tree node[maxn];        //node[maxn]為線段樹處理陣列

int a[maxn];            //a[maxn]為原陣列

void pushup(int i)

//建立乙個tree 

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

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

build(i << 1, l, mid);// 建立mid左邊的樹 i<<1所表示的是 tree 上的所在點 

build((i << 1) | 1, mid + 1, r); //建立mid右邊的樹採用遞推 

pushup(i);

}int getsum(int i, int l, int r)

else if (l > mid)

else 

}int getmax(int i, int l, int r)

else if (l>mid) 

else 

}void add(int i, int k, int v)            //當前更新的節點的編號為i(一般是1為初始編號,具體得看建立樹時使用的第乙個編號是什麼)。

int mid = (node[i].l + node[i].r) / 2;

if (k <= mid) a

else 

pushup(i);

}區間的update

const int n = 100005;

ll a[n];                    //a[n]儲存原陣列

ll  lazy[n << 2];            //lazy用來記錄該節點的每個數值應該加多少 

int n, q;

struct tree

}tree[n<<2];        

void pushup(int rt)

void pushdown(int rt,int m)

}void build(int l, int r, int rt)

int m = tree[rt].mid();

build(l, m, (rt << 1));

build(m + 1, r, (rt << 1 | 1));

pushup(rt);

}void update(ll c, int l, int r, int rt)

if (tree[rt].l == tree[rt].r)return;

int m = tree[rt].mid();

pushdown(rt, tree[rt].r - tree[rt].l + 1);

if (r <= m)update(c, l, r, rt << 1);

else if (l > m)update(c, l, r, rt << 1 | 1);

else 

pushup(rt);

}ll query(int l, int r, int rt)

int m = tree[rt].mid();

pushdown(rt, tree[rt].r - tree[rt].l + 1);

ll res = 0;

if (r <= m)res += query(l, r, rt << 1);

else if (l > m)res += query(l, r, rt << 1 | 1);

else

return res;

}

線段樹模板(模板)

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