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
| #include<bits/stdc++.h> using namespace std; const int N = 1e4 + 15; int n, m; int a[N]; struct Tree{ int l, r; int val; int num; }T[N << 2]; void build(int pos, int l, int r){ T[pos].l = l, T[pos].r = r; if(l == r){ T[pos].val = a[l]; return ; } int mid = (l + r) >> 1; build(pos << 1, l, mid); build(pos << 1 | 1, mid+1, r); T[pos].val = T[pos << 1].val + T[pos << 1 | 1].val; } void spread(int pos){ if(T[pos].num){ T[pos << 1].val += T[pos].num * (T[pos << 1].r - T[pos << 1].l + 1); T[pos << 1 | 1].val += T[pos].num * (T[pos << 1 | 1].r - T[pos << 1 | 1].l + 1); T[pos << 1].num += T[pos].num; T[pos << 1 | 1].num += T[pos].num; T[pos].num = 0; } } void update(int pos, int x, int y, int k){ if(x <= T[pos].l && y >= T[pos].r){ T[pos].val += k * (T[pos].r - T[pos].l + 1); T[pos].num += k; return ; } spread(pos); int mid = (T[pos].r + T[pos].l) >> 1; if(x <= mid) update(pos << 1, x, y, k); if(y > mid) update(pos << 1 | 1, x, y, k); T[pos].val = T[pos << 1].val + T[pos << 1 | 1].val; } int query(int pos, int x, int y){ int res = 0; if(x <= T[pos].l && y >= T[pos].r) return T[pos].val; spread(pos); int mid = (T[pos].r + T[pos].l) >> 1; if(x <= mid) res += query(pos << 1, x, y); if(y > mid) res += query(pos << 1 | 1, x, y); return res; } int main(){ scanf("%d %d", &n, &m); for(int i = 1; i <= n; i ++) scanf("%d", &a[i]); build(1, 1, n); for(int i = 1; i <= m; i ++){ int c, x, y, k; scanf("%d %d %d", &c, &x, &y); if(c == 1){ scanf("%d", &k); update(1, x, y, k); } else printf("%d\n", query(1, x, y)); } return 0; }
|