自己看:https://blog.csdn.net/weq2011/article/details/128791426
看懂就没问题了
单点修改+区间查询
https://www.luogu.com.cn/problem/P3374
#include <bits/stdc++.h> #define int long long using namespace std; const int N=5e5+5; int n, m, x, y, op, w[N], k, tr[4*N]; void build(int id, int L, int R) { if (L==R) { tr[id]=w[L]; return ; } int mid=(L+R)>>1; build(id*2, L, mid); build(id*2+1, mid+1, R); tr[id]=tr[id*2]+tr[id*2+1]; } void change(int id, int L, int R, int x, int v) { if (L==R) { tr[id]+=v; return ; } int mid=(L+R)>>1; if (x<=mid) change(id*2, L, mid, x, v); else change(id*2+1, mid+1, R, x, v); tr[id]=tr[id*2]+tr[id*2+1]; } int find(int id, int L, int R, int x, int y) { if (x<=L && R<=y) return tr[id]; int mid=(L+R)>>1, res=0; if (x<=mid) res+=find(id*2, L, mid, x, y); if (y>=mid+1) res+=find(id*2+1, mid+1, R, x, y); return res; } signed main() { scanf("%lld%lld", &n, &m); for (int i=1; i<=n; i++) scanf("%lld", &w[i]); build(1, 1, n); for (int i=1; i<=m; i++) { scanf("%lld", &op); if (op==1) { scanf("%lld%lld", &x, &k); change(1, 1, n, x, k); } else if (op==2) { scanf("%lld%lld", &x, &y); printf("%lld\n", find(1, 1, n, x, y)); } } return 0; }
区间修改+区间查询
https://www.luogu.com.cn/problem/P3372
#include <bits/stdc++.h> #define int long long using namespace std; const int N=1e5+5; struct node { int lazy, sum; }tr[4*N]; int n, m, x, y, op, w[N], k; void build(int id, int L, int R) { if (L==R) { tr[id].sum=w[L]; return ; } int mid=(L+R)>>1; build(id*2, L, mid); build(id*2+1, mid+1, R); tr[id].sum=tr[id*2].sum+tr[id*2+1].sum; } void push_down(int id, int L, int R) { if (tr[id].lazy!=0) { int mid=(L+R)>>1; tr[id*2].lazy+=tr[id].lazy; tr[id*2+1].lazy+=tr[id].lazy; tr[id*2].sum+=tr[id].lazy*(mid-L+1); tr[id*2+1].sum+=tr[id].lazy*(R-(mid+1)+1); tr[id].lazy=0; } } void push_up(int id) { tr[id].sum=tr[id*2].sum+tr[id*2+1].sum; } void change(int id, int L, int R, int x, int y, int v) { if (x<=L && R<=y) { tr[id].lazy+=v; tr[id].sum+=v*(R-L+1); return ; } push_down(id, L, R); int mid=(L+R)>>1; if (x<=mid) change(id*2, L, mid, x, y, v); if (y>=mid+1) change(id*2+1, mid+1, R, x, y, v); push_up(id); } int find(int id, int L, int R, int x, int y) { if (x<=L && R<=y) return tr[id].sum; push_down(id, L, R); int mid=(L+R)>>1; int res=0; if (x<=mid) res+=find(id*2, L, mid, x, y); if (y>=mid+1) res+=find(id*2+1, mid+1, R, x, y); return res; } signed main() { scanf("%lld%lld", &n, &m); for (int i=1; i<=n; i++) scanf("%lld", &w[i]); build(1, 1, n); for (int i=1; i<=m; i++) { scanf("%lld", &op); if (op==1) { scanf("%lld%lld%lld", &x, &y, &k); change(1, 1, n, x, y, k); } else if (op==2) { scanf("%lld%lld", &x, &y); printf("%lld\n", find(1, 1, n, x, y)); } } return 0; }
标签:lazy,int,sum,tr,mid,id,线段 From: https://www.cnblogs.com/didiao233/p/18319717