Header Ad

HackerEarth AND operation problem solution

In this HckerEarth AND operation problem solution you are given an array A of length N. You are also given Q tasks. Each task is of the following type:

  1. L R V: Apply the bitwise-and operator with V for all Ai where L <= i <= R
  2. You need to print the array after performing all the tasks.

HackerEarth AND operation problem solution


HackerEarth AND operation problem solution.

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

int main() {
vector<int> mp[32];
int n,q;
cin>>n>>q;
for(int i=0;i<n;i++){
long x;
cin>>x;
for(int j=0;j<32;j++){
if(x%2) mp[j].push_back(i+1);
x/=2;
}
}
for(int i=0;i<q;i++){
int l,r,val;
cin>>l>>r>>val;
for(int j=0;j<32;j++){
if(val%2==0){
auto it1=lower_bound(mp[j].begin(),mp[j].end(),l);
auto it2=lower_bound(mp[j].begin(),mp[j].end(),r+1);
if(it1!=it2) mp[j].erase(it1,it2);
}
val/=2;
}
}
int ans[n+5];
memset(ans,0,sizeof(ans));
for(int i=0;i<32;i++){
auto it=mp[i].begin();
for(;it!=mp[i].end();++it) ans[*it]+=(pow(2,i));
}
for(int i=1;i<=n;i++) cout<<ans[i]<<" ";
return 0;
}

Second solution

#include<bits/stdc++.h>
using namespace std;
int cnt[100005][32];
vector<int> AND_Queries (vector<int> Arr, vector<int> Val, vector<int> L, int N, int Q, vector<int> R) {
for(int i=0;i<Q;i++)
{
int l=L[i],r=R[i],v=Val[i];
for(int j=0;j<30;j++)
{
if(! (v&(1<<j)))
{
cnt[l-1][j]++;
cnt[r][j]--;
}
}
}
for(int i=0;i<Arr.size();i++)
{
int num=0;
for(int j=0;j<30;j++)
{
if(i)cnt[i][j]+=cnt[i-1][j];
if(cnt[i][j]){}
else
{
if(Arr[i]&(1<<j))num|=1<<j;
}
}
Arr[i]=num;
}
return Arr;
}

int main() {

ios::sync_with_stdio(0);
cin.tie(0);
int N;
cin >> N;
int Q;
cin >> Q;
vector<int> Arr(N);
for(int i_Arr=0; i_Arr<N; i_Arr++)
{
cin >> Arr[i_Arr];
}
vector<int> L(Q),R(Q),Val(Q);
for(int i_L=0; i_L<Q; i_L++)
{
cin >> L[i_L] >> R[i_L] >> Val[i_L];
}

vector<int> out_;
out_ = AND_Queries(Arr, Val, L, N, Q, R);
cout << out_[0];
for(int i_out_=1; i_out_<out_.size(); i_out_++)
{
cout << " " << out_[i_out_];
}
}

Post a Comment

0 Comments