- Choose the aggregate stored for each interval or prefix.
- Build or initialize the structure from the input.
- Apply updates and combine the affected nodes to answer each query.
Code notes
- 85 lines of C++ from the credited upstream file 2569.cpp.
- The implementation visibly relies on sequence storage.
- 1 loop block detected.
Complexity
Count the build once, then multiply the logarithmic update or query path by the number of operations.
Check the problem constraints before deciding whether this complexity will pass.
Use this to learn the idea, then write your own version.
1class LazySegmentTree {2 public:3 explicit LazySegmentTree(const vector<int>& nums) {4 const int n = nums.size();5 tree.resize(4 * n);6 lazy.resize(4 * n);7 build(nums, 0, 0, n - 1);8 }9 10 11 12 13 void updateRange(int i, int start, int end, int l, int r) {14 if (lazy[i])15 propogate(i, start, end);16 if (start > r || end < l)17 return;18 if (start >= l && end <= r) {19 flip(i, start, end);20 return;21 }22 const int mid = (start + end) / 2;23 updateRange(i * 2 + 1, start, mid, l, r);24 updateRange(i * 2 + 2, mid + 1, end, l, r);25 tree[i] = tree[2 * i + 1] + tree[2 * i + 2];26 }27 28 int getTreeSum() const {29 return tree[0];30 }31 32 private:33 vector<int> tree;34 vector<bool> lazy;35 36 void build(const vector<int>& nums, int i, int start, int end) {37 if (start == end) {38 tree[i] = nums[start];39 return;40 }41 const int mid = (start + end) / 2;42 build(nums, 2 * i + 1, start, mid);43 build(nums, 2 * i + 2, mid + 1, end);44 tree[i] = tree[2 * i + 1] + tree[2 * i + 2];45 }46 47 void propogate(int i, int start, int end) {48 flip(i, start, end);49 lazy[i] = false;50 }51 52 void flip(int i, int start, int end) {53 tree[i] = (end - start + 1) - tree[i]; 54 if (start < end) {55 lazy[2 * i + 1] = !lazy[2 * i + 1];56 lazy[2 * i + 2] = !lazy[2 * i + 2];57 }58 }59};60 61class Solution {62 public:63 vector<long long> handleQuery(vector<int>& nums1, vector<int>& nums2,64 vector<vector<int>>& queries) {65 vector<long long> ans;66 LazySegmentTree tree(nums1);67 long sumNums2 = accumulate(nums2.begin(), nums2.end(), 0L);68 69 for (const vector<int>& query : queries) {70 const int type = query[0];71 const int l = query[1];72 const int r = query[2];73 if (type == 1) {74 tree.updateRange(0, 0, nums1.size() - 1, l, r);75 } else if (type == 2) {76 sumNums2 += static_cast<long>(l) * tree.getTreeSum();77 } else { 78 ans.push_back(sumNums2);79 }80 }81 82 return ans;83 }84};85