测试题目:P3372 【模板】线段树 1 https://www.luogu.org/problemnew/show/P3372
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<iostream>
#include<string>
#include<vector>
#include<stack>
#include<bitset>
#include<cstdlib>
#include<cmath>
#include<set>
#include<list>
#include<deque>
#include<map>
#include<queue>
#define lson l,m,rt << 1
#define rson m+1,r,rt << 1|1
using namespace std;
inline void fast(){ios_base::sync_with_stdio(0); cin.tie(0); cout.tie(0);}
typedef long long ll;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int INF = 0x3f3f3f3f;
const int maxn = 1e5+10;
const int mod = 1000;
int n,m,T;
ll sum[maxn << 2];//记录区间和
ll add[maxn << 2];//记录区间标记
struct Node{
int l,r;
int mid(){
return (l + r) >> 1;
}
}tree[maxn << 2]; //每个数组都要开4倍空间
void PushUp(int rt){
sum[rt] = sum[rt << 1] + sum[rt << 1|1];//父节点等于两个子节点的和
}
void PushDown(int rt,int len){
if(add[rt]){ //如果存在标记
add[rt << 1] += add[rt]; //把标记向下传递
add[rt << 1|1] += add[rt];
sum[rt << 1] += (ll)add[rt]*(len - (len >> 1)); //此处要开ll 不然可能回炸int,乘上区间长度
sum[rt << 1|1] += (ll)add[rt]*(len >> 1);
add[rt] = 0; //标记归零
}
}
void BuildTree(int l,int r,int rt){
tree[rt].l = l; tree[rt].r = r; //对区间进行初始化
if(l == r){ //如果左右区间相等,到达了最终节点,此时这个节点的和就是它本身,直接输入
cin >> sum[rt];
return ;
}
int m = tree[rt].mid();
BuildTree(lson); //分别向左右建树
BuildTree(rson);
PushUp(rt);//向上传递他们的和
}
void UpdataTree(int c,int l,int r,int rt){
if(tree[rt].l == l && tree[rt].r == r){ //如果找到了我们需要修改的区间
add[rt] += c; //打上标记
sum[rt] += (ll)c*(r - l + 1); //增加区间长度 ,还是要开ll
return ;
}
PushDown(rt,tree[rt].r - tree[rt].l + 1); //每次更改都向下把这个延迟标记传递下去
int m = tree[rt].mid();
if(r <= m) //如果我要查询的右区间比我的标准中值要小,我需要向左查询
UpdataTree(c,l,r,rt << 1);
else if(l > m) //反之,如果我的左区间比标准区间大,我向右查询
UpdataTree(c,l,r,rt << 1|1);
else {
UpdataTree(c,lson); //如果再中间,要向两边查询
UpdataTree(c,rson);
}
PushUp(rt);
}
ll Query(int l,int r,int rt){
if(tree[rt].l == l && tree[rt].r == r)
return sum[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 {
res += Query(lson) + Query(rson);
}
return res;
}
int main()
{
fast();
while(cin >> n >> m){
memset(sum,0,sizeof(sum));
memset(add,0,sizeof(add));
BuildTree(1,n,1);
while(m--){
int op,x,y,k;
cin >> op;
if(op == 1){
cin >> x >> y >> k;
UpdataTree(k,x,y,1);
} else {
cin >> x >> y;
printf("%lld\n",Query(x,y,1));
}
}
}
return 0;
}