XOR of a submatrix queries in C++


In this problem, we are given a N x N matrix and some queries, each query contains the top-left and bottom-right corner of the submatrix created from this matrix. Our task is to find the XOR of all elements of the submatrix defined by the querries.

Let’s take an example to understand the problem,

Input

arr[][] = {{1, 2, 3}
{4, 5, 6}
{7, 8, 9}}
Querries: {0,0, 1,2} , {1, 2, 2, 2}

Output

1 15

Explaination

querry 1 : 1^2^3^4^5^6
querry 2 : 6^9

To solve this problem, we will find a prefix-XOR matrix to solve queries. The value of the matrix at position (R, C) is the XOR of sub-matrix from top-left corner (0, 0) and bottom-right corner at position (R, C).

We will first find prefix-XOR for all rows of matrix one by one. Then calculate the prefix XOR for each column one by one.

For finding XOR of sub-matrix to a query given by (r1, c1) to (r2, c2) is calculated using prefixXor[r2][c2] ^ prefixXor[r1-1][c2] ^ prefixXor[r2][c1-1] ^ prefixXor[r1-1][c1-1].

Program to show the implementation of our solution,

Example

 Live Demo

#include <iostream>
using namespace std;
#define n 3
void preXOR(int arr[][n], int prefix_xor[][n]) {
   for (int i = 0; i < n; i++)
      for (int j = 0; j < n; j++) {
         if (j == 0)
            prefix_xor[i][j] = arr[i][j];
         else
         prefix_xor[i][j]
            = (prefix_xor[i][j - 1] ^ arr[i][j]);
      }
   for (int i = 0; i < n; i++)
      for (int j = 1; j < n; j++)
         prefix_xor[j][i]
            = (prefix_xor[j - 1][i] ^ prefix_xor[j][i]);
}
int XORSubMatrix(int prefix_xor[][n], int querry[2]) {
   int xor_1 = 0, xor_2 = 0, xor_3 = 0;
   if (querry[0] != 0)
      xor_1 = prefix_xor[querry[0] - 1][querry[3]];
   if (querry[1] != 0)
      xor_2 = prefix_xor[querry[2]][querry[1] - 1];
   if (querry[2] != 0 and querry[1] != 0)
      xor_3 = prefix_xor[querry[0] - 1][querry[1] - 1];
   return ((prefix_xor[querry[2]][querry[3]] ^ xor_1) ^ (xor_2 ^ xor_3));
}
int main() {
   int arr[][n] = { { 1, 2, 3 },
      { 4, 5, 6 },
      { 7, 8, 9 } };
   int prefix_xor[n][n];
   preXOR(arr, prefix_xor);
   int querry1[] = {0,0, 2,2} ;
   int querry2[] = {1,2, 2,2} ;
   cout<<"The XOR of submatrix created by querries :\n";
   cout<<"Querry 1 : "<<XORSubMatrix(prefix_xor, querry1)<<endl;
   cout<<"Querry 2 : "<<XORSubMatrix(prefix_xor, querry2)<<endl;
   return 0;
}

Output

Querry 1 : 1
Querry 2 : 15


Updated on: 17-Apr-2020

82 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements