struct node{
int l,r; ll sum,lazy;
}tree[maxn * 4]; // 開四倍大小
void push_up(int root){
tree[root].sum = tree[root << 1].sum + tree[(root << 1) | 1].sum;
} // 兒子的值相加爲父親的值
void push_down(int root){
if(tree[root].lazy){ //有懶惰值
tree[root << 1].lazy += tree[(root << 1) | 1].lazy;
tree[(root << 1) | 1].lazy += tree[root].lazy;//向下傳遞懶惰值
tree[root << 1].sum += tree[root].lazy;
tree[(root << 1) | 1].sum += tree[root].lazy; //根據題目要求處理
tree[root].lazy = 0;
}
}
void build_tree(int l,int r,int root){
tree[root].lazy = 0;
tree[root].l = l;
tree[root].r = r;
if(l == r){
tree[root].sum = 1; // 這裏給一個初始值
return ;
}
int mid = (l + r) >> 1;
build_tree(l,mid,root << 1);
build_tree(mid + 1,r,(root << 1) | 1);
push_up(root); //向上更新值
}
void update_interval(int l,int r,int v,int root){ //區間更新
if(l <= tree[root].l && r >= tree[root].r){
tree[root].lazy = +v; // 保存懶惰值
tree[root].sum += v;
return ;
}
if(tree[root].lazy)
push_down(root);
int mid = (tree[root].l + tree[root].r) >> 1;
if(l <= mid)
update_interval(l,r,v,root << 1);
if(r > mid)
update_interval(l,r,v,(root << 1) | 1);
push_up(root);
}
int query_interval(int l,int r,int root){ // 區間查詢
if(l <= tree[root].l && r >= tree[root].r)
return tree[root].sum;
if(tree[root].lazy) // 查詢中遇到未更新的值,進行更新
push_down(root);
int mid = (tree[root].l + tree[root].r) >> 1;
int ans = 0;
if(l <= mid)
ans += query_interval(l,r,root << 1);
if(r > mid)
ans += query_interval(l,r,(root << 1) | 1);
return ans;
}
void update_single(int p,int v,int root){ //單點更新
if(tree[root].l == tree[root].r && tree[root].r == p){
tree[root].sum = v;
return ;
}
int mid = (tree[root].l + tree[root].r) >> 1;
if(p <= mid)
return update_single(p,v,root << 1);
else
return update_single(p,v,(root << 1) | 1);
push_up(root); //每個點更新都要向上更新值
}
int query_single(int p,int root){ //單點查詢
if(tree[root].l == tree[root].r && tree[root].r == p){
return tree[root].sum;
}
if(tree[root].lazy)
push_down(root);
int mid = (tree[root].l + tree[root].r) >> 1;
if(p <= mid)
query_single(p,root << 1);
else
query_single(p,(root << 1) | 1);
}
線段樹模板
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.