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
| class SegmentTree { class Node { Node l, r; int val, lazy; } Node root = new Node(); void pushDown(Node cur, int l, int r) { if (cur.l == null) cur.l = new Node(); if (cur.r == null) cur.r = new Node(); int m = l + (r - l) / 2; cur.l.val += cur.lazy * (m - l + 1); cur.r.val += cur.lazy * (r - m); cur.l.lazy += cur.lazy; cur.r.lazy += cur.lazy; cur.lazy = 0; } void pushUp(Node cur) { cur.val = cur.l.val + cur.r.val; } void upd(Node cur, int l, int r, int tl, int tr, int val) { if (tl <= l && r <= tr) { cur.val += val * (r - l + 1); cur.lazy += val; } else { pushDown(cur, l, r); int mid = l + (r - l) / 2; if (tl <= mid) upd(cur.l, l, mid, tl, tr, val); if (mid < tr) upd(cur.r, mid + 1, r, tl, tr, val); pushUp(cur); } } int query(Node cur, int l, int r, int tl, int tr) { if (tl <= l && r <= tr) { return cur.val; } else { pushDown(cur, l, r); int mid = l + (r - l) / 2; int res = 0; if (tl <= mid) res += query(cur.l, l, mid, tl, tr); if (mid < tr) res += query(cur.r, mid + 1, r, tl, tr); pushUp(cur); return res; } } void build(Node cur, int l, int r, int[] nums) { if (l == r) { cur.val = nums[l]; } else { int mid = l + (r - l) / 2; pushDown(cur, l, r); build(cur.l, l, mid, nums); build(cur.r, mid + 1, r, nums); pushUp(cur); } } }
|