1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| #include<iostream> #include<cstring> #include<cstdio> #include<algorithm>
using namespace std;
struct tree{ long long sum,lazy; tree *lson,*rson; tree() { lazy = 0; } };
long long x,y,k,n,m,s;
void built(tree *tre,int l,int r) { tre -> lazy = 0; if(l == r) { scanf("%d",&x); tre -> sum = x; return ; } int mid = (l + r) >> 1; tree *son1 =(tree*) malloc (sizeof(tree)); tree *son2 =(tree*) malloc (sizeof(tree)); tre -> lson = son1; tre -> rson = son2; built(tre -> lson,l,mid); built(tre -> rson,mid + 1,r); tre -> sum = tre -> lson -> sum + tre -> rson -> sum; } void pushdown(tree *tre,int l,int r) { if(l != r) { int mid = (l + r) >> 1; tre -> lson -> lazy = tre -> lson -> lazy + tre -> lazy; tre -> lson -> sum = tre -> lson -> sum + tre -> lazy * (mid - l + 1); tre -> rson -> lazy = tre -> rson -> lazy + tre -> lazy; tre -> rson -> sum = tre -> rson -> sum + tre -> lazy * (r - mid); } tre -> lazy = 0; } void change(tree *tre,int l,int r,int x,int y,int k) { if(l >= x && r <= y) { tre -> lazy += k; tre -> sum = tre -> sum + k * (r - l + 1); return ; } pushdown(tre,l,r); int mid = (l + r) >> 1; if(x <= mid) change(tre -> lson,l,mid,x,y,k); if(y > mid) change(tre -> rson,mid + 1,r,x,y,k); tre -> sum = tre -> lson -> sum + tre -> rson ->sum; }
long long query(tree *tre,int l,int r,int x,int y) { if(l >= x && r <= y) return tre -> sum; pushdown(tre,l,r); int mid = (l + r) >> 1; long long t1 = 0,t2 = 0; if(x <= mid) t1 = query(tre -> lson,l,mid,x,y); if(y > mid) t2 = query(tre -> rson,mid + 1,r,x,y); return t1 + t2; }
int main() { scanf("%lld%lld",&n,&m); tree *root = (tree*) malloc (sizeof(tree)); built(root,1,n); for(int i = 1;i <= m; i++) { scanf("%lld%lld%lld",&s,&x,&y); if(s == 1) { scanf("%lld",&k); change(root,1,n,x,y,k); } else { long long ans = query(root,1,n,x,y); printf("%lld\n",ans); } } return 0; }
|