Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- https://practice.geeksforgeeks.org/contest/job-a-thon-18-hiring-challenge/problems/#
- Given two arrays A1, A2 both of size N, Q queries. Each query contains 5 elements, [k,l1,l2,r1,r2], where l1, l2 is the 1 based indexed range of A1, and r1, r2 is the 1 based indexed range of A2. Task is to find number of pairs such that A1[i]^A2[j] has the kth bit set, where l1<=i<=l2 and r1<=j<=r2.
- Input
- A1={1,2,3,4,5}
- A2={1,2,3,4,5}
- Queries=[[2,2,4,1,3] , [1,1,1,3,5]]
- Output
- 4 1
- Explaination
- For 1st query
- Segment from A1->{2,3,4}
- Segment from A2->{1,2,3}
- Possible pairs (arr[i],arr[j])=(2,1), (3,1), (4,2), (4,3) are the only pairs who have kth bit set when pair is XORed.
- For 2nd query
- Only pair will be (1,4)
- ---------------------------------------------------------------------------------------------------------------------------------------
- class Solution {
- public:
- vector<long long int> xorPairs(int N, vector<int> &A1, vector<int> &A2, int Q, vector<vector<int>> &query) {
- vector<vector<pair<long long,long long>>> dp1(N,vector<pair<long long,long long>>(31,{0,0})); // zero,ones bit set
- vector<vector<pair<long long,long long>>> dp2(N,vector<pair<long long,long long>>(31,{0,0}));
- for(int i=0;i<N;i++){
- for(int bit=0;bit<=30;bit++){
- if(A1[i] & (1<<bit)){
- dp1[i][bit].second++;
- }
- else{
- dp1[i][bit].first++;
- }
- if(A2[i] & (1<<bit)){
- dp2[i][bit].second++;
- }
- else{
- dp2[i][bit].first++;
- }
- if(i-1>=0){
- dp1[i][bit].second+=dp1[i-1][bit].second;
- dp1[i][bit].first+=dp1[i-1][bit].first;
- dp2[i][bit].second+=dp2[i-1][bit].second;
- dp2[i][bit].first+=dp2[i-1][bit].first;
- }
- }
- }
- vector<long long int> res;
- for(auto q: query){
- int k=q[0]-1;
- int l1=q[1]-1;
- int l2=q[2]-1;
- int r1=q[3]-1;
- int r2=q[4]-1;
- long long zerosL=dp1[l2][k].first;
- long long onesL=dp1[l2][k].second;
- if(l1-1>=0){
- zerosL-=dp1[l1-1][k].first;
- onesL-=dp1[l1-1][k].second;
- }
- long long zerosR=dp2[r2][k].first;
- long long onesR=dp2[r2][k].second;
- if(r1-1>=0){
- onesR-=dp2[r1-1][k].second;
- zerosR-=dp2[r1-1][k].first;
- }
- long long int ans=onesR*zerosL+zerosR*onesL;
- res.push_back(ans);
- }
- return res;
- }
- };
Advertisement
Add Comment
Please, Sign In to add comment