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
| int a[n + 1]; int tree[n * 4 + 1]; int tag[n * 4 + 1]; void pushdown(int p, int l, int r) { int mid = l + r >> 1; tag[p * 2] += tag[p]; tag[p * 2 + 1] += tag[p]; tree[p * 2] += tag[p] * (mid - l + 1); tree[p * 2 + 1] += tag[p] * (r - mid); tag[p] = 0; } void pushup(int p) { tree[p] = tree[p * 2] + tree[p * 2 + 1]; } void build(int p, int l, int r) { if(l == r) { tree[p] = a[l]; return; } int mid = l + r >> 1; build(p * 2, l, mid); build(p * 2 + 1, mid + 1, r); pushup(p); } void update(int val, int ql, int qr, int p, int l, int r) { if(ql <= l && r <= qr) { tag[p] += val; tree[p] += val * (r - l + 1); return; } int mid = l + r >> 1; pushdown(p, l, r); if(ql <= mid) update(val, ql, qr, p * 2, l, mid); if(mid < qr) update(val, qr, qr, p * 2 + 1, mid + 1, r); pushup(p); } int query(int ql, int qr, int p, int l, int r) { if(ql <= l && r <= qr) return tree[p]; int res = 0; int mid = l + r >> 1; pushdown(p); if(ql <= mid) res += query(ql, qr, p * 2, l, mid); if(mid < qr) res += query(ql, qr, p * 2 + 1, mid + 1, r); return res; }
|