private void buildTree(int l, int r) { if (l < 0 || r < 0 || r < l) throw new IllegalArgumentException("Illegal range: ("+l+","+r+")"); minPos = l; maxPos = r; // Reached leaf if (l == r - 1) { left = right = null; // Add children } else { int mid = (l + r) / 2; left = new Node(l, mid); right = new Node(mid, r); } }
public int sum(int l, int r) { // Do lazy updates to children propagate(); // Node's range fits inside query range if (l <= minPos && maxPos <= r) return sum; // Ranges do not overlap else if (r <= minPos || l >= maxPos) return 0; // Ranges partially overlap else return (left == null ? 0 : left.sum(l, r)) + (right == null ? 0 : right.sum(l, r)); }
public int min(int l, int r) { // Do lazy updates to children propagate(); // Node's range fits inside query range if (l <= minPos && maxPos <= r) return min; // Ranges do not overlap else if (r <= minPos || l >= maxPos) return INF; // Ranges partially overlap else return Math.min((left == null ? INF : left.min(l, r)), (right == null ? INF : right.min(l, r))); }
public void update(int l, int r, int change) { // Do lazy updates to children propagate(); // Node's range fits inside query range if (l <= minPos && maxPos <= r) { sum += change * (maxPos - minPos); min += change; // Lazily propagate update to children if (left != null) left.lazy += change; if (right != null) right.lazy += change; // Ranges do not overlap } else if (r <= minPos || l >= maxPos) { // Do nothing // Ranges partially overlap } else { if (left != null) left.update(l, r, change); if (right != null) right.update(l, r, change); sum = (left == null ? 0 : left.sum) + (right == null ? 0 : right.sum); min = Math.min((left == null ? INF : left.min), (right == null ? INF : right.min)); } }
private Node(int l, int r) { buildTree(l, r); }
public Node(int sz) { buildTree(0, sz); }
@Test(expected=IllegalArgumentException.class) public void testIllegalSegmentTreeCreation2() { int size = -10; Node tree = new Node(size); }
@Test(expected=IllegalArgumentException.class) public void testIllegalSegmentTreeCreation1() { Node tree = new Node(null); }