#include <bits/stdc++.h>
using namespace std;
const int N = 1000005;
int n, m, p, x, y, a[N], sum[4 * N];
inline void pushup(int rt)
{
sum[rt] = sum[rt << 1] + sum[rt << 1 | 1];
}
inline void build(int l, int r, int rt)//建树
{
if(l == r){ sum[rt] = a[l]; return;}
int mid = (l + r) >> 1;
build(l, mid, rt << 1);
build(mid + 1, r, rt << 1 | 1);
pushup(rt);
}
inline void update(int l, int r, int rt, int x, int d)//单点修改
{
if(l == r){ sum[rt] = d; return;}
int mid = (l + r) >> 1;
if(x <= mid) update(l, mid, rt << 1, x, d);
else update(mid + 1, r, rt << 1 | 1, x, d);
pushup(rt);
}
inline int query(int l, int r, int rt, int x, int y)//区间查询
{
if(x <= l && r <= y) return sum[rt];//区间[l,r]包含[x,y]
int mid = (l + r) >> 1;
int res = 0;
if(x <= mid) res += query(l, mid, rt << 1, x, y);
if(y > mid) res += query(mid + 1, r, rt << 1 | 1, x, y);
return res;
}
int main()
{
int m, n;
cin >> m >> n;
memset(a, 127, sizeof(a));
for(int i = 1; i <= m; i++) cin >> a[i];
build(1, m, 1);//建树
for(int i = 1; i <= n; i++){
cin >> p >> x >> y;
if(p == 1) cout << query(1, m, 1, x, y) << " ";
else update(1, m, 1, x, y);
}
return 0;
}
Lazytag
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e6 + 1e5;
int n, m, q, l, r, x;
int a[N], add[N], sum[4 * N];
void pushup(int rt)
{
sum[rt] = sum[rt << 1] + sum[rt << 1 | 1];
}
void pushdown(int rt, int l, int r)
{
if(add[rt] == 0) return;
add[rt << 1] += add[rt];
add[rt << 1 | 1] += add[rt];
sum[rt << 1] += add[rt] * l;
sum[rt << 1 | 1] += add[rt] * r;
add[rt] = 0;
}
void build(int l, int r, int rt)//建树
{
if(l == r){ sum[rt] = a[l]; return;}
int mid = (l + r) >> 1;
build(l, mid, rt << 1);
build(mid + 1, r, rt << 1 | 1);
pushup(rt);
}
void update(int l, int r, int rt, int x, int d)//单点修改
{
if(l == r){ sum[rt] = d; return;}
int mid = (l + r) >> 1;
if(x <= mid) update(l, mid, rt << 1, x, d);
else update(mid + 1, r, rt << 1 | 1, x, d);
pushup(rt);
}
void modify(int x, int y, int d, int l, int r, int rt)//区间修改[x,y]+d
{
if(x <= l && y >= r){
sum[rt] += d * (r - l + 1);//当前的[l,r]都在[x,y]范围内
add[rt] += d;//标记
return;
}
int mid = (l + r) >> 1;
pushdown(rt, mid - l + 1, r - mid);
if(x <= mid) modify(x, y, d, l, mid, rt << 1);
if(y > mid) modify(x, y, d, mid + 1, r, rt << 1 | 1);
pushup(rt);
}
int query(int l, int r, int rt, int x, int y)//区间查询
{
if(x > r || y < l) return 0;
if(x <= l && r <= y) return sum[rt];//区间[x,y]包含[l,r]
int mid = (l + r) >> 1;
pushdown(rt, mid - l + 1, r - mid);
int ans = 0;
if(x <= mid) ans += query(l, mid, rt << 1, x, y);
if(y > mid) ans += query(mid + 1, r, rt << 1 | 1, x, y);
return ans;
}
signed main()
{
cin >> n >> m;
for(int i = 1; i <= n; i++) cin >> a[i];
build(1, n, 1);//建树
for(int i = 1; i <= m; i++){
cin >> q >> l >> r;
if(q == 1){
cin >> x;
modify(l, r, x, 1, n, 1);
}
else cout << query(1, n, 1, l, r) << "\n";
}
return 0;
}