Xor Rectangle

You have an array of N integers 

S1,S2,...SN. Consider a N x N matrix such that Ai,j=SiSj. Here  indicates bitwise xor operator.
You have been given Q queries. Each query consists of four integers x1,y1,x2,y2 which denotes a submatrix with (x1,y1) as their top-left corner and (x2,y2) as their bottom-right corner such that x1x2 and y1y2. For each of the query, you have to print summation of all integers lying in queried submatrix.

Example:

Input:  n = 4, a = {1, 2, 3, 4},q = 2, queries = {{1, 2, 3, 4}, {1, 1, 1, 1}}

Output:

25 0

Approach:

C++

#include <bits/stdc++.h>
using namespace std;

int arr[1000005];
int tree[1000005][20];

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    int n = 4;
    vector<inta = {1234};
    int q = 2;
    vector<vector<int>> queries = {{1234},
                                   {1111}};

    for (int i = 1i <= ni++)
    {
        arr[i] = a[i - 1];
    }

    int x1x2y1y2;

    for (int i = 1i <= ni++)
    {
        for (int j = 0j < 20j++)
        {
            tree[i][j] = tree[i - 1][j] + (1 & (arr[i] >> j));
        }
    }

    for (int i = 0i < qi++)
    {
        x1 = queries[i][0];
        y1 = queries[i][1];
        x2 = queries[i][2];
        y2 = queries[i][3];

        long long ans = 0;
        int w = x2 - x1 + 1h = y2 - y1 + 1ab;

        for (int i = 0i < 20i++)
        {
            a = (tree[x2][i] - tree[x1 - 1][i]);
            b = (tree[y2][i] - tree[y1 - 1][i]);

            ans += (1LL << i) * (a * (h - b) + b * (w - a));
        }

        cout << ans << "\n";
    }

    return 0;
}


No comments:

Post a Comment