lazy 线段树代码
描述
代码:
1 class Node { 2 int l, r; 3 int sum; 4 int lazy; 5 } 6 7 class SegmentTree { 8 9 private Node[] tree; 10 11 private int[] nums; 12 13 public SegmentTree(int[] nums) { 14 int n = nums.length; 15 this.nums = nums; 16 tree = new Node[n << 2]; 17 for (int i = 0; i < tree.length; i++) { 18 tree[i] = new Node(); 19 } 20 build(1, 1, n); 21 } 22 23 24 public void build(int node, int left, int right) { 25 tree[node].l = left; 26 tree[node].r = right; 27 if (left == right) { 28 tree[node].sum = nums[left - 1]; 29 return; 30 } 31 int mid = (left + right) >> 1; 32 build(node << 1, left, mid); 33 build(node << 1 | 1, mid + 1, right); 34 pushUp(node); 35 } 36 37 public void pushUp(int node) { 38 tree[node].sum = tree[node << 1].sum + tree[node << 1 | 1].sum; 39 } 40 41 public void modify(int node, int left, int right) { 42 // 修改区间大于该节点区间范围 43 if (tree[node].l >= left && tree[node].r <= right) { 44 tree[node].sum += tree[node].r - tree[node].l + 1; 45 tree[node].lazy ^= 1; 46 return; 47 } 48 pushDown(node); 49 50 int mid = (tree[node].l + tree[node].r) >> 1; 51 if (left <= mid) { 52 modify(node << 1, left, right); 53 } 54 if (right > mid) { 55 modify(node << 1 | 1, left, right); 56 } 57 pushUp(node); 58 } 59 60 public void pushDown(int node) { 61 if (tree[node].lazy == 1) { 62 int mid = (tree[node].l + tree[node].r) >> 1; 63 tree[node << 1].sum += mid - tree[node << 1].l + 1; 64 tree[node << 1].lazy ^= 1; 65 tree[node << 1 | 1].sum += tree[node << 1 | 1].r - mid; 66 tree[node << 1 | 1].lazy ^= 1; 67 tree[node].lazy ^= 1; 68 } 69 } 70 71 public int query(int node, int left, int right) { 72 if (tree[node].l >= left && tree[node].r <= right) { 73 return tree[node].sum; 74 } 75 pushDown(node); 76 int mid = (tree[node].l + tree[node].r) >> 1; 77 int res = 0; 78 if (left <= mid) { 79 res += query(node << 1, left, right); 80 } 81 if (right > mid) { 82 res += query(node << 1 | 1, left, right); 83 } 84 return res; 85 } 86 87 } 88 89 class Solution{ 90 public static void main(String[] args) { 91 int[] nums = {5,6,7,8}; 92 SegmentTree segmentTree = new SegmentTree(nums); 93 segmentTree.modify(1, 1, 3); 94 int res = segmentTree.query(1, 2, 4); 95 System.out.println(res); 96 97 } 98 }