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 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161
| public static class SegmentTree { private int MAXN; private int[] arr; private int[] sum; private int[] lazy; private int[] change; private boolean[] update;
public SegmentTree(int[] origin) { MAXN = origin.length + 1; arr = new int[MAXN]; for (int i = 1; i < MAXN; i++) { arr[i] = origin[i - 1]; } sum = new int[MAXN << 2];
lazy = new int[MAXN << 2]; change = new int[MAXN << 2]; update = new boolean[MAXN << 2]; } private void pushUp(int rt) { sum[rt] = sum[rt << 1] + sum[rt << 1 | 1]; }
private void pushDown(int rt, int ln, int rn) { if (update[rt]) { update[rt << 1] = true; change[rt << 1] = change[rt]; lazy[rt << 1] = 0; sum[rt << 1] = change[rt] * ln; update[rt << 1 | 1] = true; change[rt << 1 | 1] = change[rt]; lazy[rt << 1 | 1] = 0; sum[rt << 1 | 1] = change[rt] * rn; update[rt] = false; } if (lazy[rt] != 0) { lazy[rt << 1] += lazy[rt]; sum[rt << 1] += lazy[rt] * ln; lazy[rt << 1 | 1] += lazy[rt]; sum[rt << 1 | 1] += lazy[rt] * rn; lazy[rt] = 0; } }
public void build(int l, int r, int rt) { if (l == r) { sum[rt] = arr[l]; return; } int mid = (l + r) >> 1; build(l, mid, rt << 1); build(mid + 1, r, rt << 1 | 1); pushUp(rt); } public void add( int L, int R, int C, int l, int r, int rt) { if (L <= l && r <= R) { sum[rt] += C * (r - l + 1); lazy[rt] += C; return; } int mid = (l + r) >> 1; pushDown(rt, mid - l + 1, r - mid); if (L <= mid) { add(L, R, C, l, mid, rt << 1); } if (R > mid) { add(L, R, C, mid + 1, r, rt << 1 | 1); } pushUp(rt); } public void update(int L, int R, int C, int l, int r, int rt) { if (L <= l && r <= R) { update[rt] = true; change[rt] = C; sum[rt] = C * (r - l + 1); lazy[rt] = 0; return; } int mid = (l + r) >> 1; pushDown(rt, mid - l + 1, r - mid); if (L <= mid) { update(L, R, C, l, mid, rt << 1); } if (R > mid) { update(L, R, C, mid + 1, r, rt << 1 | 1); } pushUp(rt); }
public long query(int L, int R, int l, int r, int rt) { if (L <= l && r <= R) { return sum[rt]; } int mid = (l + r) >> 1; pushDown(rt, mid - l + 1, r - mid); long ans = 0; if (L <= mid) { ans += query(L, R, l, mid, rt << 1); } if (R > mid) { ans += query(L, R, mid + 1, r, rt << 1 | 1); } return ans; }
}
|