[Codeforces 341D] Iahub and Xors — Solution
Main Idea
First, seeing this problem, you could consider a tree of trees, and then you're done.
Let's consider using a 2D Fenwick tree to take differences. Of course, if we take differences the usual way, all we can think of is using prefix sums to maintain point values, not range XOR sums. Let the result after differencing be:
\[ d_{i, j} = a_{i, j} \oplus a_{i - 1, j} \oplus a_{i, j - 1} \oplus a_{i - 1, j - 1} \]
This way of differencing is a bit different, because compared with the traditional difference we additionally count the contribution of \(a_{i - 1, j - 1}\).
Whenever we do a region operation, by association with 2D differencing, we roughly know that operating on \(d_{x_1, y_1}, d_{x_2 + 1, y_1}, d_{x_1, y_2 + 1}, d_{x_2 + 1, y_2 + 1}\) achieves the goal. So let's think about how, once this 2D differencing is done, we compute range XOR sums. Here, we use \(\sum\) to denote the result of a range XOR sum:
\[ ans = \sum_{i = 1}^{x} \sum_{j = 1}^{y} a_{i, j} \]
Forcibly substitute the definition of \(d_{i, j}\):
\[ ans = \sum_{i = x_1}^{x_2} \sum_{j = y_1}^{y_2} d_{i, j} \oplus a_{i - 1, j} \oplus a_{i, j - 1} \oplus a_{i - 1, j - 1} \]
It finally becomes:
\[ ans = \sum_{i = 2k + (x \bmod 2)}^x \sum_{j = 2k + (y \bmod 2)}^y d_{i, j} \]
So taking differences directly here makes sense. We can set up 4 2D Fenwick trees by the parity of \((x, y)\), and then just work by parity.
Code
// CF341D.cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAX_N = 1010;
int n, q;
struct BIT
{
inline int lowbit(int x) { return x & (-x); }
ll nodes[MAX_N][MAX_N];
void update(int x, int y, ll d)
{
for (int i = x; i <= n; i += lowbit(i))
for (int j = y; j <= n; j += lowbit(j))
nodes[i][j] ^= d;
}
ll query(int x, int y)
{
ll ret = 0;
for (int i = x; i >= 1; i -= lowbit(i))
for (int j = y; j >= 1; j -= lowbit(j))
ret ^= nodes[i][j];
return ret;
}
} tr[4];
int getParity(int x, int y) { return (x & 1) | ((y & 1) << 1); }
void modify(int x, int y, ll d) { tr[getParity(x, y)].update(x, y, d); }
ll query(int x, int y) { return tr[getParity(x, y)].query(x, y); }
int main()
{
scanf("%d%d", &n, &q);
while (q--)
{
int opt, x1, y1, x2, y2;
ll d;
scanf("%d%d%d%d%d", &opt, &x1, &y1, &x2, &y2);
if (opt == 1)
{
ll ans = 0;
ans ^= query(x2, y2);
ans ^= query(x1 - 1, y2);
ans ^= query(x2, y1 - 1);
ans ^= query(x1 - 1, y1 - 1);
printf("%lld\n", ans);
}
else
{
scanf("%lld", &d), modify(x1, y1, d);
modify(x2 + 1, y1, d), modify(x1, y2 + 1, d);
modify(x2 + 1, y2 + 1, d);
}
}
return 0;
}