You have an array of N integers
. Consider a N x N matrix such that . Here indicates bitwise xor operator.
You have been given Q queries. Each query consists of four integers which denotes a submatrix with () as their top-left corner and () as their bottom-right corner such that and . 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<int> a = {1, 2, 3, 4};int q = 2;vector<vector<int>> queries = {{1, 2, 3, 4},{1, 1, 1, 1}};for (int i = 1; i <= n; i++){arr[i] = a[i - 1];}int x1, x2, y1, y2;for (int i = 1; i <= n; i++){for (int j = 0; j < 20; j++){tree[i][j] = tree[i - 1][j] + (1 & (arr[i] >> j));}}for (int i = 0; i < q; i++){x1 = queries[i][0];y1 = queries[i][1];x2 = queries[i][2];y2 = queries[i][3];long long ans = 0;int w = x2 - x1 + 1, h = y2 - y1 + 1, a, b;for (int i = 0; i < 20; i++){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