[LeetCode] Handling Sum Queries After Update

2569. Handling Sum Queries After Update

You are given two 0-indexed arrays nums1 and nums2 and a 2D array queries of queries. There are three types of queries:

  1. For a query of type 1, queries[i] = [1, l, r]. Flip the values from 0 to 1 and from 1 to 0 in nums1 from index l to index r. Both l and r are 0-indexed.
  2. For a query of type 2, queries[i] = [2, p, 0]. For every index 0 <= i < n, set nums2[i] = nums2[i] + nums1[i] * p.
  3. For a query of type 3, queries[i] = [3, 0, 0]. Find the sum of the elements in nums2.

Return an array containing all the answers to the third type queries.

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
struct Seg {
long long mi, ma, sum;
bool lazy;
Seg *left, *right;
Seg(vector<int>& A, int l, int r) : mi(l), ma(r), sum(0), lazy(false), left(nullptr), right(nullptr) {
if(l != r) {
int m = l + (r - l) / 2;
left = new Seg(A,l,m);
right = new Seg(A,m+1,r);
sum = left->sum + right->sum;
} else sum = A[l];
}
void propagate() {
if(lazy) {
sum = (ma - mi + 1) - sum;
if(left and right) {
left->lazy = !left->lazy;
right->lazy = !right->lazy;
}
lazy = false;
}
}
void filp(int l, int r) {
propagate();
if(mi > r or ma < l) return;
if(l <= mi and ma <= r) {
lazy = !lazy;
propagate();
} else {
propagate();
left->filp(l,r);
right->filp(l,r);
sum = left->sum + right->sum;
}
}
long long query() {
propagate();
return sum;
}
};

class Solution {
public:
vector<long long> handleQuery(vector<int>& nums1, vector<int>& nums2, vector<vector<int>>& queries) {
Seg* seg = new Seg(nums1, 0, nums1.size() - 1);
long long now = accumulate(begin(nums2), end(nums2), 0ll);
vector<long long> res;
for(auto q : queries) {
long long op = q[0], l = q[1], r = q[2];
if(op == 1) seg->filp(l,r);
if(op == 2) now += seg->query() * l;
if(op == 3) res.push_back(now);
}
return res;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2023/02/19/PS/LeetCode/handling-sum-queries-after-update/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.