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
| class Solution { int N = (int)1e9; class Node { Node l, r; int val, lazy; } Node root = new Node(); public List<Integer> fallingSquares(int[][] positions) { List<Integer> ans = new ArrayList<>(); for (int[] info : positions) { int x = info[0], h = info[1], cur = query(root, 0, N, x, x + h - 1); update(root, 0, N, x, x + h - 1, cur + h); ans.add(root.val); } return ans; } private int query(Node node, int start, int end, int left, int right) { if (node == null) return 0; updateLazy(node, start, end); if (left <= start && end <= right) return node.val; int mid = start + (end - start) / 2; int ans = 0; if (left <= mid) { if (node.l == null) { node.l = new Node(); node.l.val = node.val; } ans = query(node.l, start, mid, left, right); } if (mid + 1 <= right) { if (node.r == null) { node.r = new Node(); node.r.val = node.val; } ans = Math.max(ans, query(node.r, mid + 1, end, left, right)); } return ans; } private void updateLazy(Node node, int start, int end) { if (node.lazy != 0) { node.val = node.lazy; if (start != end) { if (node.l != null) node.l.lazy = node.lazy; if (node.r != null) node.r.lazy = node.lazy; } node.lazy = 0; } } private void update(Node node, int start, int end, int left, int right, int newValue) { if (node == null) return; if (left <= start && end <= right) { node.val = newValue; node.lazy = 0; if (node.l != null) node.l.lazy = newValue; if (node.r != null) node.r.lazy = newValue; return; } int mid = start + (end - start) / 2; if (node.l == null) { node.l = new Node(); node.l.val = node.val; } if (node.r == null) { node.r = new Node(); node.r.val = node.val; } if (left <= mid) { update(node.l, start, mid, left, right, newValue); } if (mid + 1 <= right) { update(node.r, mid + 1, end, left, right, newValue); } node.val = Math.max(node.l.val, node.r.val); } }
|