You've got an array a, consisting of n integers a1, a2, ..., an. You are allowed to perform two operations on this array:
Calculate the sum of current array elements on the segment [l, r], that is, count value al + al + 1 + ... + ar.
Apply the xor operation with a given number x to each array element on the segment [l, r], that is, execute . This operation changes exactly r - l + 1 array elements.
Expression means applying bitwise xor operation to numbers x and y. The given operation exists in all modern programming languages, for example in language C++ and Java it is marked as "^", in Pascal — as "xor".
You've got a list of m operations of the indicated type. Your task is to perform all given operations, for each sum query you should print the result you get.
Input
The first line contains integer n (1 ≤ n ≤ 105) — the size of the array. The second line contains space-separated integers a1, a2, ..., an (0 ≤ ai ≤ 106) — the original array.
The third line contains integer m (1 ≤ m ≤ 5·104) — the number of operations with the array. The i-th of the following m lines first contains an integer ti (1 ≤ ti ≤ 2) — the type of the i-th query. If ti = 1, then this is the query of the sum, if ti = 2, then this is the query to change array elements. If the i-th operation is of type 1, then next follow two integers li, ri (1 ≤ li ≤ ri ≤ n). If the i-th operation is of type 2, then next follow three integers li, ri, xi (1 ≤ li ≤ ri ≤ n, 1 ≤ xi ≤ 106). The numbers on the lines are separated by single spaces.
Output
For each query of type 1 print in a single line the sum of numbers on the given segment. Print the answers to the queries in the order in which the queries go in the input.
Please, do not use the %lld specifier to read or write 64-bit integers in С++. It is preferred to use the cin, cout streams, or the %I64d specifier.
We need to process an array of up to 100k elements, with up to 50k operations. Each operation is either a range sum query or a range XOR update (apply XOR with a given x to each element in the range). XOR is bitwise, so it's not a simple additive update. The numbers are up to 1e6, which is about 20 bits.
We need efficient handling: typically O((n+m) log n) or similar.
The problem: we need to support range XOR updates and range sum queries. This is not directly supported by a standard BIT or segment tree with lazy propagation because XOR doesn't combine nicely with sum. However we can break down by bits: Since numbers are up to 1e6 (~20 bits), we could maintain for each bit a segment tree that stores the count of 1s in that bit for each segment. Then a range XOR update with x toggles bits where x has 1: for each bit b where x's b-th bit is 1, we need to flip the bits in that range, i.e., the count of ones becomes (length - count). The sum of the array can be computed from bits: sum = Σ_b (count_one[b] * (1<<b)). So we can maintain 20 segment trees (or one segment tree storing a bitset of length 20 and also sum? Actually we can store for each node the sum of the segment, and also perhaps a lazy XOR tag? But if we store sum directly, we need to know how to update sum under XOR with x. That's not linear: XOR with x changes each element's value unpredictably. However we can compute the new sum after XOR by knowing the current bit counts: for each bit b, if x's bit b is 1, then the contribution of that bit to sum becomes (length - count) * (1<<b) instead of count * (1<<b). So if we know the current sum and the bit counts, we can update. But we also need to propagate lazy tags: If we maintain segment tree with lazy XOR on each node, we need to apply the XOR to the node's sum? For a segment, if we have a lazy XOR value t to apply to the whole segment, then the new sum can be computed if we know the bit counts per segment. Alternatively we can store both sum and an array of bit counts for each segment. But that would be 20 integers per node, which with n=1e5 leads to about 210^5 nodes, times 20 ~ 4e6 integers, which is okay memory wise (4e6 * 4 bytes = 16 MB). However segment tree with size about 4n ~ 4e5, times 20 = 8e6, still okay. But we can also store sum and a bitmask lazy tag, and compute the effect of XOR on sum using also the bitwise components. However we still need to know, for each node, the distribution of bits to update correctly. So simplest: store for each node an array counts[0..MAXB-1] (maybe up to 20 bits). Actually numbers up to 1e6 < 2^20=1,048,576, so 20 bits (0..19). So we need counts for each bit. Then for each node we also can compute sum on the fly from counts, but storing sum separately might be faster.
We also need lazy XOR tag: when we apply XOR with x to a segment, we need to update the counts: for each bit b where x has 1, count_one becomes length - count_one. That can be done in O(number of bits) per node update. And we also need to propagate lazy tag to children: if we have a pending XOR to apply to the whole segment, we can combine tags by XOR. So we can implement a segment tree with lazy propagation where each node stores: length of segment (or we can compute from indices), and an array cnt[20] of counts of ones for each bit. Or we can store as a single integer representing the sum, but updating sum directly requires knowing counts. So better to store counts.
Range XOR update: apply XOR with x on segment [l, r]. Recursively traverse, push lazy down when needed. For a node fully covered, we update its cnt: for each bit b where (x>>b)&1, cnt[b] = len - cnt[b]. Also update lazy tag: node.lazy ^= x. (Initially 0)
Range sum query: compute sum over [l, r] by traversing and summing contributions. But we need to return sum, not per-bit counts. However we can compute sum from the cnt arrays returned from the query. However if we combine nodes, we can sum their cnt arrays or sum their sums. To avoid creating per-query bit arrays, we can compute sum on the fly: if we return a struct containing sum (or cnt). Usually, we can implement query to return the sum directly: When we get to a node fully covered, we can compute its sum from its cnt (or store sum separately). To combine partial nodes we need to add sums. If we store sum in each node and keep it updated after each update (by recomputing from cnt after applying lazy), we can just sum the sum values. That's easier: maintain node.sum = Σ_b cnt[b] * (1<<b). When we update cnt for XOR, we recompute sum accordingly. So node stores sum and cnt[20], and lazy tag. After applying XOR, we recompute sum.
Segment tree size: typical implementation with arrays of size 4n. For each node we need an array of 20 ints (maybe 32-bit). That's 4n20 = 8 million for n=1e5 (since 41e5=400k, times 20 = 8 million). 8 million ints = 32 MB. Plus sum (8 bytes maybe) and lazy (4 bytes) and maybe length derived from indices. This might be okay, but memory limit? Not specified but typical 256 MB, so 32 MB is fine. However careful: 8 million ints * 4 bytes = 32 MB. Add sum (8 bytes per node) ~3.2 MB, lazy ~1.6 MB, plus overhead for tree structure. So total maybe 40-50 MB, acceptable.
But we could reduce memory by storing cnt as bitset of 20 bits? But we need counts, not just presence. So we need integer counts. However length up to 1e5, counts up to length, fit in int (32-bit). So it's fine.
Alternative: use binary indexed tree of bits? But range XOR update and range sum query: we can use segment tree with lazy XOR and also maintain sum via bit contributions.
Given constraints m up to 5e4, and n up to 1e5, O(m * log n * 20) ~ 5e4 * 17 * 20 ≈ 17 million, which is fine.
Alternatively, we could use sqrt decomposition: break into blocks of size B ~ sqrt(n) ~ 316, maintain block sum and a lazy XOR tag per block, and for each element we store its value. But applying XOR to a range that partially covers blocks requires updating individual elements (O(B) per block). But we need to also compute sum quickly. With 5e4 operations, sqrt decomposition might be okay: each operation O(sqrt(n) * B?) Actually typical: range update (XOR) on segment: we iterate over blocks. For fully covered blocks, we apply the XOR to the block's lazy tag and update block sum accordingly (by flipping bits using count of ones per bit? That again requires per-bit counts in block). So we would need per-block bit counts. So similar complexity. So segment tree seems easier.
Thus implement a segment tree with per-node bit counts and lazy XOR.
Plan:
Determine MAXB = 20 (since 2^20 = 1,048,576 > 1e6). Actually maximum ai <= 1e6, so 20 bits (bits 0..19). But note that xi can be up to 1e6, also within 20 bits.
For each node, store:
sum: long long (64-bit)
cnt[20]: int array (or maybe we can store as vector but fixed size)
lazy: int (xor tag, initially 0)
We also might store the length of the segment (or compute from tree build parameters). Could store len for each node to avoid passing it; but we can compute on the fly: node's segment length = r - l + 1. During build, we set len for each node. Or we can compute from indices when needed; easier to store len.
Segment tree implementation:
Build: recursively build from array a. For leaf, len =1, sum = a[l], cnt[b] = ((a[l]>>b) & 1). For internal node, combine children: sum = left.sum + right.sum, cnt[b] = left.cnt[b] + right.cnt[b], len = left.len + right.len.
Push lazy: function apply(node, x):
For each bit b where (x>>b) & 1:
node.cnt[b] = node.len - node.cnt[b];
node.sum = Σ (node.cnt[b] * (1<<b));
node.lazy ^= x; // combine pending
But careful: When we apply XOR x to a node, we need to update the node's sum. However we also have to be aware that if node already has a lazy tag, we combine: new lazy = node.lazy ^ x. When we later push down, we apply the combined lazy to children.
So push(node) function: if node.lazy != 0:
apply(left_child, node.lazy);
apply(right_child, node.lazy);
node.lazy = 0;
Update range: function update(node, l, r, ql, qr, x):
if segment [l,r] fully inside [ql,qr]: apply(node, x); return.
push(node);
recurse to children if overlap.
after children updates, pull(node): recompute sum and cnt from children.
Query range: function query(node, l, r, ql, qr):
if fully inside: return node.sum.
push(node);
sum = 0;
if overlap left: sum += query(left)
if overlap right: sum += query(right)
return sum.
But note: we may not need to push for query if we are only reading sum? Actually if we have lazy tag pending, node.sum is already up-to-date because we updated node.sum when applying lazy. In our design, when we apply lazy we immediately updated node's sum and cnt. So node.sum is correct for the node's segment, even if lazy is non-zero (the lazy indicates that children are not updated yet). So for query, when we descend, we need to push the lazy to children to ensure that if we query a subrange that partially overlaps, the children sums are correct. So yes, we need to push before recursing to children, just like for update.
Alternatively, we can avoid push in query if we always combine from children? But if we go into children, they might not have correct sums because lazy not applied. So we push.
Thus we need to implement push for both update and query.
Edge Cases: large n, recursion depth? For segment tree recursion depth ~ log2(100k) ~ 17, safe. But recursion for building might cause stack overflow if implemented recursively for each node? Usually safe. However we can implement iterative segment tree? Recursive is fine.
Now complexity: Each update, for each node fully covered we apply XOR x: this loops over 20 bits, so O(20) per node. And push also loops over 20 bits? Actually push applies the lazy to children: that also uses apply(child, lazy) which loops 20 bits. So each push also O(20). So total operations O(20 * number of nodes visited) which is O(20 * log n) per query? Actually each update may visit O(log n) nodes, but due to lazy, we apply to O(log n) nodes at the top, and then push may occur on some nodes during recursion. In worst case, the number of nodes visited is O(log n) (the path to the leaf) but also we may visit many nodes if the range is large? Standard segment tree: each range update touches O(log n) nodes (the ones fully covered) plus some nodes on the boundaries. Actually the number of nodes touched is O(log n) for each level? More precisely, the segment tree recursion for range update typically visits O(log n) nodes: you go down the tree, and at each level you may split, but total number of nodes visited is about 4*log n? Actually it's O(log n) for the number of segments that partition the range. In practice, the number of visited nodes is O(log n) for the size of the tree, but more precisely it's O(log n) for each operation, but the constant factor might be larger because we traverse both children if overlap partially. However still O(log n) nodes per operation.
Thus overall complexity O((n + m) * 20 * log n) ~ about 1e5 * 20 * 17 = 34 million for build, plus 5e4 * 20 * 17 = 17 million for queries, total ~50 million, which is fine.
Memory: We'll implement using arrays for tree nodes:
Define:
size = 4 * n (or 4 * n + 5)
long long sum[size];
int lazy[size];
vector<vector> cnt? Could use a 2D array: cnt[size][MAXB]. But that's huge: size=400000, MAXB=20 -> 8 million ints. That's okay as a global 2D static array: int cnt[4MAXN][MAXB]? But MAXN=100000 -> 4100000=400000. 40000020=8,000,000, each int 4 bytes = 32 MB. Plus sum 4000008=3.2MB, lazy 400000*4=1.6MB, total ~37 MB. Plus other overhead, still okay. But global static array of size 400000 * 20 = 8 million ints, might be near memory limit but typical Codeforces 256 MB. So fine.
But careful: In C++, declaring a 2D static array of that size inside a function may cause stack overflow because it's on the stack. We should allocate it on heap using vector, or declare it as global. Better: use global arrays:
const int MAX = 1 << 17? Actually we can compute next power of two? But using 4*n is fine.
We'll define:
const int MAXN = 100000;
const int MAXB = 20;
const int N = 100000; // actual n
int n, m;
vector sum;
vector lazy;
vector<vector> cnt;
Initialize after reading n: resize sum to 4n, lazy to 4n, cnt to 4*n vector of size MAXB.
Alternatively, we can define arrays dynamically:
int cnt[4MAXN][MAXB]; // if MAXN=100000, 4100000=400000, 400000*20=8e6, might be okay as global.
But to be safe and not to exceed compile-time memory, we can use vectors.
Segment tree functions:
void build(int node, int l, int r, vector& a) {
if(l == r) {
sum[node] = a[l];
for(int b=0; b<MAXB; ++b) {
cnt[node][b] = (a[l] >> b) & 1;
}
// len? we can compute when needed; but for apply we need node length. We can store len[node] = r-l+1, but easier: we can compute on the fly by passing length. For apply, we need length. So we might store len array: len[node] = r - l + 1; We'll compute during build and store per node. Or we can compute from l,r when applying, but apply may be called with node without l,r known? In push, we call apply on children with their lengths. We can precompute len for each node. So build can set len[node] = r - l + 1. Use a vector len.
Thus we need len array: vector len; resize to 4*n, fill during build.
We'll have:
len[node] = r - l + 1;
But for leaves it's 1.
Alternatively, we can pass length as parameter to apply. In push, we know the children's lengths? Since push is called on a node with known l,r? In our recursion, we usually have l and r. So we can compute mid, and children lengths: left_len = mid - l + 1, right_len = r - mid. Then in apply, we pass len as argument. So we don't need to store len array. That may be simpler: apply(node, x, length). For internal nodes we can compute length from l and r passed.
Thus we define: void apply(int node, int x, int length) {
if (x == 0) return;
for(int b=0; b<MAXB; ++b) {
if((x>>b)&1) {
cnt[node][b] = length - cnt[node][b];
}
}
// recompute sum
long long s = 0;
for(int b=0; b<MAXB; ++b) {
s += (long long) cnt[node][b] * (1LL << b);
}
sum[node] = s;
lazy[node] ^= x;
}
In build, we call apply only on leaves? Not needed. For leaves we set directly.
Thus we need to ensure that when we call apply, we know the length. In update when we fully cover a node, we have l and r, so length = r - l + 1. In push, we call apply on children; we know the children's segment lengths if we know the parent's segment boundaries. So we need to pass that length.
Thus we will implement segment tree recursively with parameters l, r. In update, when we fully cover, we call apply(node, x, r - l + 1). In push, we need to push lazy to left and right children. But we need the lengths of those children. Since push is called from a node that has known l and r, we can compute mid and then lengths: left_len = mid - l + 1, right_len = r - mid. Then apply(left_child, lazy[node], left_len); apply(right_child, lazy[node], right_len); Then set lazy[node]=0.
Thus we need to implement push(node, l, r) that uses mid.
But careful: In query we also push before recursing; we need to know l,r to compute mid.
Thus our functions:
build(node, l, r, a)
apply(node, x, len)
push(node, l, r) // only if lazy != 0
update(node, l, r, ql, qr, x)
query(node, l, r, ql, qr) returns long long
Implementation details:
We'll use 1-indexed array indexing for input, and our segment tree indices from 1 to n.
The node indexing: root=1, left=2node, right=2node+1.
Now the main algorithm:
Read n.
Read array a[1..n].
Build segment tree.
Read m.
For each operation:
read type.
if type == 1:
read l, r.
print query(1, 1, n, l, r)
else:
read l, r, x.
update(1, 1, n, l, r, x)
Edge Cases:
Input numbers up to 1e6, but sum can be up to n * 1e6 = 1e11, fits in 64-bit.
XOR updates can be with x up to 1e6, but we treat as int.
Testing with examples.
Example 1:
5
4 10 3 13 7
8
1 2 4 -> sum of indices 2..4: 10+3+13=26, prints 26
2 1 3 3 -> XOR 3 on [1,3]: 4^3=7,10^3=9,3^3=0 => [7,9,0,13,7]
1 2 4 -> sum indices 2..4: 9+0+13=22 -> prints 22
1 3 3 -> index 3: 0 -> prints 0
2 2 5 5 -> XOR 5 on [2,5]: 9^5=12,0^5=5,13^5=8,7^5=2 => [7,12,5,8,2]
1 1 5 -> sum=7+12+5+8+2=34 -> prints 34
2 1 2 10 -> XOR 10 on [1,2]: 7^10=13,12^10=6 => [13,6,5,8,2]
1 2 3 -> indices 2..3:6+5=11 -> prints 11
Matches output.
Now we implement.
Potential pitfalls:
Use 0-index vs 1-index? We'll adopt 1-index for array and queries.
In apply, we need to recompute sum after updating cnt. Could also compute delta sum to avoid loop over bits, but loops over 20 bits is fine.
In push, after applying lazy to children, set lazy[node]=0.
In update, after recursing to children, we need to pull node: recompute sum and cnt from children. Write a function pull(node) that does: for each bit: cnt[node][b] = cnt[left][b] + cnt[right][b]; sum[node] = sum[left] + sum[right]; This requires left and right indices; we can compute left=node2, right=node2+1. So we can implement pull(node) without l,r.
Similarly, build uses pull for internal nodes.
Now about MAXB: Since numbers up to 1e6, bits from 0 to 19. But note that xi may be up to 1e6, but could have bit 20? 2^20 = 1,048,576 > 1e6, but xi <= 1e6, so max is 2^20? Actually 1,000,000 in binary is 11110100001001000000 (20 bits), but the highest set bit is bit 19 (since 2^19=524288, 2^20=1,048,576 > 1e6). So bits 0-19 inclusive: 20 bits. However check: 2^19=524288, 2^20=1,048,576 > 1e6, so numbers up to 1e6 can only have bits 0..19 (20 bits). So MAXB = 20.
But we may consider up to 20 bits just in case xi = 1e6 = 11110100001001000000 (which uses bit 19). So fine.
But what if we have numbers like 0? That's fine.
Now performance: In apply we loop over all 20 bits every time. Could optimize by only looping over set bits of x (popcount). But popcount of x <= 20 anyway, but average maybe less. However we can just loop all bits; it's fine.
Implementation details: Use 1-index for cnt? We'll have cnt as vector of vectors: cnt = vector<vector> (4n, vector(MAXB,0)); But initializing 4n * MAXB zeros might be costly but okay for n=1e5? 400k20=8 million zeros. That's okay. However we might allocate exactly 4n only after reading n; we can do cnt.resize(4*n, vector(MAXB,0)); But that would allocate and set to 0 for all, which is fine. But we also need to fill during build. But if we allocate and fill with 0, we still need to set them in build. It's okay.
But perhaps we can use dynamic memory: int cnt[4MAXN][MAXB] as global outside main; then we can use n to define the used part. But global static arrays must have constant size. So we can set MAXN = 100000, and size = 4MAXN+5. That uses memory even if n is smaller, but still 4*100000=400k, same. So we can just use constant max size.
Option: define const int N = 100000; const int SZ = 4*N+5; then arrays sum[SZ], lazy[SZ], cnt[SZ][20]. This is okay and avoids dynamic allocation overhead. But it's global and fixed size; if n is less, we still use same memory. That's fine.
I'll choose to use global arrays with maximum size: e.g., const int MAX = 100000; const int SZ = 4*MAX+5; const int B = 20; Then declare:
long long sum[SZ];
int lazy[SZ];
int cnt[SZ][B];
But then build will set values only for used nodes up to 4*n. This is fine.
Potential stack overflow? No, global arrays are in data segment, not stack.
Now, note: B=20, but we must be careful to use (1<<b) for b up to 19, but (1<<19) is 524288, (1<<20) would be 1,048,576; but we won't use b=20. So loops from 0 to B-1.
Now implement:
void build(int node, int l, int r, int* a) // a is 1-indexed
{
if(l==r){
sum[node] = a[l];
for(int b=0;b<B;b++) cnt[node][b] = (a[l]>>b)&1;
return;
}
int mid = (l+r)/2;
build(node2, l, mid, a);
build(node2+1, mid+1, r, a);
pull(node);
}
void apply(int node, int x, int len){
if(x==0) return;
for(int b=0;b<B;b++){
if((x>>b)&1){
cnt[node][b] = len - cnt[node][b];
}
}
// recalc sum
long long s=0;
for(int b=0;b<B;b++){
s += (long long)cnt[node][b] * (1LL<<b);
}
sum[node] = s;
lazy[node] ^= x;
}
void push(int node, int l, int r){
if(lazy[node]==0) return;
int mid = (l+r)/2;
apply(node2, lazy[node], mid-l+1);
apply(node2+1, lazy[node], r-mid);
lazy[node]=0;
}
void update(int node, int l, int r, int ql, int qr, int x){
if(ql<=l && r<=qr){
apply(node, x, r-l+1);
return;
}
push(node, l, r);
int mid = (l+r)/2;
if(ql <= mid) update(node2, l, mid, ql, qr, x);
if(qr > mid) update(node2+1, mid+1, r, ql, qr, x);
pull(node);
}
long long query(int node, int l, int r, int ql, int qr){
if(ql<=l && r<=qr) return sum[node];
push(node, l, r);
int mid = (l+r)/2;
long long res = 0;
if(ql <= mid) res += query(node2, l, mid, ql, qr);
if(qr > mid) res += query(node2+1, mid+1, r, ql, qr);
return res;
}
In main, read input, allocate array a (size n+1). Build tree.
Check: For query, we push before recursing to ensure children are up-to-date. However, when we push, we apply lazy to children. That's correct.
Potential optimization: In push, we recalc sum for children using apply. That's fine.
Now test with example.
We'll implement quickly in C++.
Consider also using fast I/O: ios::sync_with_stdio(false); cin.tie(0);
Now note: For B bits, we use 1LL<<b, but b up to 19 fits in 32-bit but we cast to long long.
Edge Cases: What if x has bits beyond B? Not possible because x <= 1e6. So safe.
Now we should verify with second example.
Second example:
6
4 7 4 0 7 3
5
2 2 3 8 -> XOR 8 on [2,3]: 7^8=15, 4^8=12 => [4,15,12,0,7,3]
1 1 5 -> sum indices 1..5: 4+15+12+0+7=38 -> prints 38
2 3 5 1 -> XOR 1 on [3,5]: 12^1=13,0^1=1,7^1=6 => [4,15,13,1,6,3]
2 4 5 6 -> XOR 6 on [4,5]: 1^6=7,6^6=0 => [4,15,13,7,0,3]
1 2 3 -> sum indices 2..3: 15+13=28 -> prints 28
Matches output.
Thus solution is correct.
Now think about alternative approaches, but this is fine.
Now we should ensure there's no bug with lazy propagation:
When we apply XOR to a node fully covered, we update its cnt and sum, and set lazy ^= x.
Later, when we push that node's lazy to children, we apply the same XOR to children using apply. apply on child will update child's cnt and sum using child's length, and also child's lazy ^= x.
After pushing, we set node's lazy to 0.
This is correct.
pull after children updates ensures node's sum and cnt reflect children.
Now, potential pitfall: apply function recalculates sum by summing over bits. However, when we call apply on a node that has pending lazy (i.e., we combine), we need to ensure that applying new XOR on top of existing lazy works: we call apply(node, x, len) when node already has some lazy value that hasn't been pushed. But note that we only call apply either when we are at a node that is fully covered (update) or when pushing (apply to child). In the update case, we may apply on a node that already has some lazy tag (from previous updates that haven't been pushed). Is that allowed? Yes, because node's current state (cnt and sum) already reflect the effect of previous lazy tags (since we updated cnt and sum when we applied those tags). So when we apply a new XOR, we need to further transform the current cnt: flipping bits according to x. This is exactly what apply does: it flips bits based on x, using the current cnt values (which are already correct). So it's fine to call apply on a node that already has a lazy tag; we just update cnt and sum, and combine lazy by XOR. That's correct: the pending operation that hasn't been pushed to children remains combined.
But careful: The node's cnt after previous apply reflected the previous XORs, but its children may not have been updated. However, that's okay because the node's cnt and sum are correct for the entire segment; the lazy indicates that children need to be updated later. When we apply another XOR on the whole segment, we can directly update node's cnt and sum again, and combine the lazy. The children will eventually get both XORs when we push. So correct.
Thus our update logic is correct.
Now about memory: Global arrays size SZ = 4*MAXN+5 = 400005; B=20; cnt[400005][20] -> 8,000,100 ints. At 4 bytes each = ~32 MB. sum[400005] of long long = 8 bytes each = ~3.2 MB. lazy[400005] = ~1.6 MB. total < 40 MB. That's fine.
But some compilers might have limits on large stack for local arrays; but we'll use global.
Now implement with B=20. We can also compute B as 20 exactly or maybe 21 to be safe? Since 1e6 fits in 20 bits, but 2^20 = 1,048,576 > 1e6, so if xi = 1,000,000, highest bit is 19, not 20. So 20 bits (0-19) covers all. However, if we consider that a number up to 10^6 can be 1,000,000, its binary representation is 11110100001001000000, which uses bits up to 19 (since 2^19 = 524288, 2^20=1,048,576 > 1e6). So indeed bits 0..19 inclusive => 20 bits. So B=20.
Now edge case: What if xi is exactly 1,048,575? That's >1e6? 1,048,575 > 1,000,000, but xi ≤ 10^6, so not possible. So 20 bits enough.
Now test with custom case: n=1, a=[0], m=1: type2: l=1,r=1,x=5 => XOR 5 -> sum becomes 5. Then type1 query -> 5.
Now think about performance: each apply loops over 20 bits, recomputes sum. That's fine.
Potential micro-optimizations: Precompute powers of two: pw[b] = 1LL<<b. Use in loops.
But not necessary.
Now code.
Potential issues: Input reading: numbers can be up to 1e6, but we use int.
Now final code.
We'll write in C++:
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100000;
const int SZ = 4 * MAXN + 5;
const int B = 20; // bits 0..19
long long sum[SZ];
int lazy[SZ];
int cnt[SZ][B];
int a[MAXN+1]; // 1-indexed input array
void push(int node, int l, int r) {
if(lazy[node] == 0) return;
int mid = (l + r) / 2;
apply(node2, lazy[node], mid - l + 1);
apply(node2+1, lazy[node], r - mid);
lazy[node] = 0;
}
void update(int node, int l, int r, int ql, int qr, int x) {
if(ql <= l && r <= qr) {
apply(node, x, r - l + 1);
return;
}
push(node, l, r);
int mid = (l + r) / 2;
if(ql <= mid) update(node2, l, mid, ql, qr, x);
if(qr > mid) update(node2+1, mid+1, r, ql, qr, x);
pull(node);
}
long long query(int node, int l, int r, int ql, int qr) {
if(ql <= l && r <= qr) {
return sum[node];
}
push(node, l, r);
int mid = (l + r) / 2;
long long res = 0;
if(ql <= mid) res += query(node2, l, mid, ql, qr);
if(qr > mid) res += query(node2+1, mid+1, r, ql, qr);
return res;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
cin >> n;
for(int i=1; i<=n; i++) cin >> a[i];
build(1, 1, n);
cin >> m;
while(m--) {
int type;
cin >> type;
if(type == 1) {
int l, r;
cin >> l >> r;
cout << query(1, 1, n, l, r) << '\n';
} else {
int l, r, x;
cin >> l >> r >> x;
update(1, 1, n, l, r, x);
}
}
return 0;
}
Now test quickly with the examples.
First example: Should output as given.
But there's a nuance: In the query, we are pushing lazy down, which is correct. However, after we push, the node's sum remains correct, but we don't recalc the node's sum? Actually after push, we haven't changed node's sum; but we have applied lazy to children, and then set lazy[node]=0. The node's sum originally was correct for the whole segment after previous updates. However, after pushing, we have updated children to reflect the lazy, but the node's sum still reflects the same total sum? Actually, sum[node] is the sum of its children's sums. But before push, sum[node] is correct because we had updated it when applying lazy. After pushing, we haven't changed sum[node] but we have updated children to also have correct sums. But sum[node] should still equal sum[left] + sum[right]? Let's verify: before push, sum[node] was correct for the segment; left and right had stale values (not yet updated). After push, we apply the lazy to left and right, which updates their sums. But we haven't updated sum[node] after that. So now sum[node] is still the old sum, which is equal to (old left sum + old right sum) (since it was computed from them originally). However, after push, left and right sums changed, so sum[node] is no longer equal to sum[left]+sum[right]. That's a problem because later if we call pull(node) again, it would recompute correctly, but if we don't call pull, the node's sum becomes inconsistent.
In standard lazy propagation, after we push lazy to children, we typically do not need to update the parent's sum because the parent's sum already incorporates the effect of that lazy (since it was applied to the parent directly). However, when we push, we are moving the lazy effect from parent to children, but the parent's sum should remain the same because the total sum of the segment hasn't changed. But we need to ensure that after pushing, the children sums become updated to reflect the lazy, and the parent sum remains the same as before. However, the parent sum is not automatically equal to the sum of its children after push unless we set it appropriately. Usually in segment tree implementations, we maintain that for any node, sum[node] = sum[left] + sum[right] regardless of lazy. But if we have lazy at node, we may store sum[node] as the correct sum for the segment (including the lazy), and the children sums are not yet updated. When we push, we apply the lazy to children, updating their sums. After pushing, we must set lazy[node]=0. But what about sum[node]? It should still represent the correct sum of the segment. However, after updating children sums, the sum of children equals the correct sum of the segment (since the lazy has been applied to them). So sum[node] should equal sum[left] + sum[right] after the push. But currently sum[node] already equals the correct sum (because it had lazy applied). And after we update children, sum[left] and sum[right] also become correct and should add up to sum[node]. So we don't need to change sum[node]; it should remain correct. But is it guaranteed that sum[node] equals sum[left] + sum[right] after push? Let's test with simple numbers.
Suppose a segment of length 2: children originally have values A and B. Node sum = A+B. Then we apply XOR x to the node. In apply(node, x, len=2), we compute new cnt and sum directly, so node.sum becomes new sum S (the sum after XOR). Also we set lazy[node] = x. Children remain unchanged. So node.sum = S, left.sum = A, right.sum = B, and S != A+B generally. This is fine.
Now later we push: we call apply(left, x, len=1) which updates left.sum to A' (A xor x). Similarly right becomes B' (B xor x). After that, we set lazy[node]=0. Now we have left.sum = A', right.sum = B'. And we know that S should equal A' + B' because XOR distributes? Actually, (A xor x) + (B xor x) is not necessarily equal to (A+B) after applying XOR to the whole segment? Wait, the operation is element-wise XOR. The sum of the segment after applying XOR to both elements is (A xor x) + (B xor x). That is S. So indeed S = A' + B'. So after push, left.sum + right.sum = A' + B' = S. So node.sum already equals S, and after push, left and right sums are correct and sum to S. So node.sum remains consistent. So we don't need to update node.sum after push. That is because we applied the same transformation to children that we had applied to the parent. So the parent sum remains correct as the total sum.
Thus our push function that only applies to children and clears lazy is fine. No need to recalc node sum.
But what if the node had multiple lazy tags combined? Still, the transformation is linear in terms of sum? Actually XOR is not linear, but the effect of applying XOR x to the whole segment is to replace each element a_i by a_i ^ x. The sum of the segment becomes Σ (a_i ^ x). This is not equal to Σ a_i after some transformation; but it's deterministic. When we apply the same x to children, the sum of children becomes exactly the sum of the segment. So parent sum should equal sum of children after both children are updated. So it's consistent.
Thus push is fine.
Now one more thing: In query, after we push, we may later call pull on ancestors? Actually not during query. Query only reads sums and pushes. It doesn't change the tree structure besides pushing, so the consistency is maintained.
Thus the implementation is correct.
Now check for potential bugs: In apply, we recompute sum by summing over all bits. But we could also compute sum by using the previous sum and length and x? But not needed.
But note: When we apply XOR to a node, we flip bits. However, after flipping bits, the new sum can be computed as sum = old sum + Σ_b ((x>>b)&1) * ((len - 2*cnt[b]) * (1<<b)). This may be faster but not needed.
Now one more detail: In build, we set lazy[node] = 0. In apply, we XOR lazy. In push we clear lazy after applying to children. All good.
Now we need to ensure that array indices are within bounds. Since n up to 100k, we use SZ = 4MAXN+5. MAXN defined as 100000. But what if n is 100000 exactly? 4100000 = 400000. Our SZ = 4MAXN+5 = 400005. That's enough. Node indexing: root 1, children up to 2node+1. In the worst case, the maximum node index could be near 4*n. So 400000 is safe.
Now, we used cnt[SZ][B] as global. This is large but okay. However, global arrays are zero-initialized by default. That's fine.
Now test with n=100000 and all operations random to see if any runtime issues. Should be fine.
Potential improvement: use bitset and counts? Not needed.
Thus final answer.
Now provide the solution description.
But the problem statement originally had images for XOR operation. We'll just describe.
Now final output as code.
We should also note to not use %lld. We used cout with long long, which is fine.
Now produce final answer with explanation and code. ```cpp
#include <bits/stdc++.h>
using namespace std;
const int MAXN = 100000; // maximum possible n
const int SZ = 4 * MAXN + 5; // segment tree size
const int B = 20; // bits: 0..19 (since a[i], x ≤ 1e6 < 2^20)
long long sum[SZ]; // segment sum
int lazy[SZ]; // pending xor to apply to the whole segment
int cnt[SZ][B]; // cnt[node][b] = number of ones in the segment for bit b
int a[MAXN + 1]; // original array (1‑based)
int n, m;
// ---------- segment tree helpers ----------
// combine children information
void pull(int node) {
sum[node] = sum[node * 2] + sum[node * 2 + 1];
for (int b = 0; b < B; ++b)
cnt[node][b] = cnt[node * 2][b] + cnt[node * 2 + 1][b];
}
// apply xor x to the whole node (segment length = len)
void apply(int node, int x, int len) {
if (x == 0) return;
// flip bits that are set in x
for (int b = 0; b < B; ++b) {
if ((x >> b) & 1) {
cnt[node][b] = len - cnt[node][b];
}
}
// recompute sum from bit counts
long long s = 0;
for (int b = 0; b < B; ++b) {
s += (long long)cnt[node][b] * (1LL << b);
}
sum[node] = s;
// combine with existing lazy tag
lazy[node] ^= x;
}
// push lazy tag to children
void push(int node, int l, int r) {
if (lazy[node] == 0) return;
int mid = (l + r) / 2;
apply(node * 2, lazy[node], mid - l + 1);
apply(node * 2 + 1, lazy[node], r - mid);
lazy[node] = 0;
}
// build tree from array a[1..n]
void build(int node, int l, int r) {
if (l == r) {
sum[node] = a[l];
for (int b = 0; b < B; ++b)
cnt[node][b] = (a[l] >> b) & 1;
lazy[node] = 0;
return;
}
int mid = (l + r) / 2;
build(node * 2, l, mid);
build(node * 2 + 1, mid + 1, r);
pull(node);
lazy[node] = 0;
}
// range xor update
void update(int node, int l, int r, int ql, int qr, int x) {
if (ql <= l && r <= qr) {
apply(node, x, r - l + 1);
return;
}
push(node, l, r);
int mid = (l + r) / 2;
if (ql <= mid) update(node * 2, l, mid, ql, qr, x);
if (qr > mid) update(node * 2 + 1, mid + 1, r, ql, qr, x);
pull(node);
}
// range sum query
long long query(int node, int l, int r, int ql, int qr) {
if (ql <= l && r <= qr) {
return sum[node];
}
push(node, l, r);
int mid = (l + r) / 2;
long long res = 0;
if (ql <= mid) res += query(node * 2, l, mid, ql, qr);
if (qr > mid) res += query(node * 2 + 1, mid + 1, r, ql, qr);
return res;
}
// ---------- main ----------
int main() {
ios::sync_with_stdio(false);
cin.tie(0);
code
cin >> n;
for (int i = 1; i <= n; ++i) cin >> a[i];
build(1, 1, n);
cin >> m;
while (m--) {
int t;
cin >> t;
if (t == 1) { // sum query
int l, r;
cin >> l >> r;
cout << query(1, 1, n, l, r) << '\n';
} else { // xor update
int l, r, x;
cin >> l >> r >> x;
update(1, 1, n, l, r, x);
}
}
return 0;