Tyrion Lannister is being put on trial for the murder of Joffrey and knows he will get no justice in Westeros. Our version of Westeros requires you to solve problems to win such trials. Make sure Tyrion wins by solving the problem given below because he's too awesome to die.
You are given an array of integers A of size N. Now you are given Q queries to be performed over this array.
In each of the queries, you are given 3 space-separated integers L, R, and X, you need to output the summation of XOR of X with each of the array elements from range L to R both inclusive ( 1-based indexing ).
In simple terms .
NOTE: Array remains the same for each of the queries.
Example:
Input: n = 5, q = 3, v = {2, 3, 1, 4, 5}, queries = {{2, 3, 7}, {1, 1, 3}, {3, 5, 2}}
Output:
10 1 16
Approach:
C++
#include <bits/stdc++.h>using namespace std;void iWantTrial(long long n, long long q, vector<long long> &v,vector<vector<long long>> &queries){vector<long long> a(n + 1, 0);vector<vector<long long>> pre(32, a);for (long long i = 0; i < 32; i++){long long mask = 1 << i;for (long long j = 0; j < n; j++){if (v[j] & mask){pre[i][j + 1] = pre[i][j] + 1;}else{pre[i][j + 1] = pre[i][j];}}}for (int i = 0; i < q; i++){long long l = queries[i][0];long long r = queries[i][1];long long x = queries[i][2];long long ans = 0;for (long long i = 0; i < 32; i++){long long mask = 1 << i;long long count;if (mask & x){count = r - l + 1 - (pre[i][r] - pre[i][l - 1]);}else{count = (pre[i][r] - pre[i][l - 1]);}ans += count * mask;}cout << ans << "\n";}}int main(){long long n = 5, q = 3;vector<long long> v = {2, 3, 1, 4, 5};vector<vector<long long>> queries = {{2, 3, 7},{1, 1, 3},{3, 5, 2}};iWantTrial(n, q, v, queries);return 0;}
No comments:
Post a Comment