/*线段数模板*/
maxn -> 最多节点数
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].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 = 0; // 这里给一个初始值
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)
update_single(p,v,root << 1);
else
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);
}